c#下载共享文件夹下的文件并记录错误日志

 public void Run()
{
//获取目标文件列表
string _ErrorMessage = "";
string _ErrorMessageFile = "errorLog.txt";
FileHelper fh = new FileHelper();
string servername = "";//服务器地址
string username = "";//用户名
string password = "";//用户密码
string filePath = "";//源文件目录
string targetFilePath = "";//目标目录 string _configtxt = "configtxt.txt";//配置文件
string _foldertxt = "foldertxt.txt";//源文件及目标目录列表 try
{
//获取配置文件
string configRes = GetFileString(_configtxt); if (configRes == "读取配置文件失败")
{
Console.WriteLine("读取配置文件失败");
_ErrorMessage = "读取配置文件失败";
WriteLog(_ErrorMessage, _ErrorMessageFile);
return;
}
//登录
Dictionary<string, string> dicconfig = GetDicFromStr(configRes);
try
{
servername = dicconfig["servername"];
username = dicconfig["username"];
password = dicconfig["password"];
}
catch
{
Console.WriteLine("配置文件错误");
_ErrorMessage = "配置文件错误";
WriteLog(_ErrorMessage, _ErrorMessageFile);
return;
}
//开始读取源文件数据
string folderRes = GetFileString(_foldertxt);
Dictionary<string, string> dicFolders = GetDicFromStr(folderRes);
string _defaultfolder = "";//默认拷贝目录
foreach (var folderdata in dicFolders)
{
if (folderdata.Key == "defaultfolder")
{
_defaultfolder = folderdata.Value;
continue;
}
filePath = folderdata.Key;//源文件目录 string temptargetFilePath = folderdata.Value == "" ? _defaultfolder : folderdata.Value;
//获取源文件后2个目录名
string toFilePath = filePath.Split('\\')[filePath.Split('\\').Length - ] + "\\" + filePath.Split('\\')[filePath.Split('\\').Length - ];
targetFilePath = temptargetFilePath.Trim('\\') + "\\" + toFilePath;//目标文件目录
if (!Directory.Exists(targetFilePath))
{
Directory.CreateDirectory(targetFilePath);
} //建立连接并且下载
if (FileHelper.connectState(servername, username, password))
{
string[] fileArr = fh.readlist(filePath);
//剪切所有文件
foreach (string filename in fileArr)
{
try
{
fh.FileMove(filename, targetFilePath.Trim('\\') + "\\" + GetFileNameFromPath(filename));
}
catch
{
Console.WriteLine(filename + " 文件下载失败"+DateTime.Now.ToString());
}
}
} } }
catch(Exception ex)
{
Console.WriteLine(ex.Message + ex.Source + ex.TargetSite);
_ErrorMessage = ex.Message + ex.Source + ex.TargetSite;
}
if (_ErrorMessage != "")
{
WriteLog(_ErrorMessage, _ErrorMessageFile);
} }
//写错误日志
private void WriteLog(string data,string logname)
{
try
{
FileMode fm = FileMode.Append;
if (!File.Exists(System.AppDomain.CurrentDomain.BaseDirectory+logname))
{
fm = FileMode.CreateNew;
}
string configfilename = System.AppDomain.CurrentDomain.BaseDirectory + logname;
//读取文本文件
FileStream fs = new FileStream(configfilename, fm);
StreamWriter sw = new StreamWriter(fs, Encoding.Default); sw.Write(DateTime.Now.ToString()+"---------"+ data); //释放占用
sw.Close();
sw.Dispose();
fs.Close();
fs.Dispose();
}
catch
{
} } private Dictionary<string, string> GetDicFromStr(string sourcestr)
{
Dictionary<string, string> dicres = new Dictionary<string, string>();
string[] datas = sourcestr.Replace("\r","").Split('\n');
foreach (string data in datas)
{
if (string.IsNullOrEmpty(data))
{
continue;
}
try
{
string[] dataarr = data.Split('=');
if (dataarr.Length == )
{ dicres.Add(dataarr[], dataarr[]);
}
else
{
dicres.Add(dataarr[], "");
}
}
catch
{ }
}
return dicres;
}
private string GetFileNameFromPath(string path)
{
return path.Split('\\')[path.Split('\\').Length - ];
}
private string GetFileString(string configname)
{
try
{
string configfilename = System.AppDomain.CurrentDomain.BaseDirectory + configname;
//读取文本文件
FileStream fs = new FileStream(configfilename, FileMode.Open);
StreamReader m_streamReader = new StreamReader(fs, Encoding.Default);
m_streamReader.BaseStream.Seek(, SeekOrigin.Begin);
//获取数据
string myFileStr = m_streamReader.ReadToEnd(); //释放占用
m_streamReader.Close();
m_streamReader.Dispose();
fs.Close();
fs.Dispose(); return myFileStr;
}
catch
{
return "读取配置文件失败";
}
}

Filehelper.cs内容

 public class FileHelper
{ System.Collections.ArrayList alst; //得到路径下所有文件(包括子文件夹下的文件)
public string[] readlist(string path)
{
alst = new System.Collections.ArrayList();//建立ArrayList对象
GetDirs(path);//得到文件夹
return (string[])alst.ToArray(typeof(string));//把ArrayList转化为string[]
} public void GetFiles(string dir)
{
try
{
string[] files = Directory.GetFiles(dir);//得到文件
foreach (string file in files)//循环文件
{
string exname = file.Substring(file.LastIndexOf(".") + );//得到后缀名
// if (".txt|.aspx".IndexOf(file.Substring(file.LastIndexOf(".") + 1)) > -1)//查找.txt .aspx结尾的文件
//if (".txt".IndexOf(file.ToLower().Substring(file.LastIndexOf(".") + 1)) > -1)//如果后缀名为.txt文件
//{
// FileInfo fi = new FileInfo(file);//建立FileInfo对象
// alst.Add(fi.FullName);//把.txt文件全名加人到FileInfo对象
//}
FileInfo fi = new FileInfo(file);//建立FileInfo对象
alst.Add(fi.FullName);
}
}
catch
{ }
} public void GetDirs(string d)//得到所有文件夹
{
GetFiles(d);//得到所有文件夹里面的文件
try
{
string[] dirs = Directory.GetDirectories(d);
foreach (string dir in dirs)
{
GetDirs(dir);//递归
}
}
catch
{
}
} //文件剪切
public void FileMove(string filePath, string toFilePath)
{
string dirPath = filePath;
string sourcePath = toFilePath;
FileInfo file = new FileInfo(dirPath);
file.MoveTo(sourcePath);
}
//建立共享文件连接
public static bool connectState(string path, string userName, string passWord)
{
bool Flag = false;
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
string dosLine = @"net use " + path + " /user:" + userName + " " + passWord ;
proc.StandardInput.WriteLine(dosLine);
proc.StandardInput.WriteLine("exit");
while (!proc.HasExited)
{
proc.WaitForExit();
}
string errormsg = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
if (string.IsNullOrEmpty(errormsg))
{
Flag = true;
}
else
{
throw new Exception(errormsg);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
proc.Close();
proc.Dispose();
}
return Flag;
} }
上一篇:tengine install


下一篇:python导入requests库一直报错原因总结 (文件名与库名冲突)