namespace AutoSync
{
enum SyncResult
{
Success,SourceDirNotExists,DestDirNotExists
}
class FloderSync
{
public int CreateDirCount = 0;
public int CopyFileCount = 0;
public List<string> Log = new List<string>();
private void AddLog(string logtext)
{
if (Log.Count < 1000)
Log.Add(System.DateTime.Now.ToString() + logtext);
else if (Log.Count == 1000)
Log.Add(System.DateTime.Now.ToString() + " 达到日志上限,不再追加");
}
public SyncResult StartSync(string sourcedir, string destdir)
{
//传入目录名保护
sourcedir = sourcedir.Trim();
destdir = destdir.Trim();
//保证目录最后一个字符不是斜杠
if (sourcedir[sourcedir.Length - 1] == '\\')
sourcedir = sourcedir.Remove(sourcedir.Length - 1);
if (destdir[destdir.Length - 1] == '\\')
destdir = destdir.Remove(destdir.Length - 1);
//判断目录是否存在
if (!Directory.Exists(sourcedir)) return SyncResult.SourceDirNotExists;
if (!Directory.Exists(destdir)) return SyncResult.DestDirNotExists;
//获取源、目的目录内的目录信息
Dictionary<string, string> SDirInfo = new Dictionary<string, string>();
Dictionary<string, string> DDirInfo = new Dictionary<string, string>();
Dictionary<string, string> aa = new Dictionary<string, string>();
SDirInfo = NewDirectory.GetDirectories(sourcedir);//获取源目录的目录信息
DDirInfo = NewDirectory.GetDirectories(destdir);//获取目标目录的目录信息
//
// 开始同步两个目录,但只先同步源目录信息
//------比较两目录中的子目录信息---------------------
foreach (KeyValuePair<string, string> kvp in SDirInfo) //在查找有无源目录存在而在目标目录中不存在的目录
{
if(!DDirInfo.ContainsKey(kvp.Key)) //如果目标目录中不存在目录,则马上建立
{
string dirname=destdir + "\\" + kvp.Key;
Directory.CreateDirectory(dirname);
AddLog(" 创建目录:" + dirname);
CreateDirCount++;
}
//递归调用目录同步函数,实现嵌套目录一次性全同步
StartSync(sourcedir + "\\" + kvp.Key, destdir + "\\" + kvp.Key);
}
//取得源目录下所有文件的列表
string[] SFiles = Directory.GetFiles(sourcedir);
//string[] DFiles = Directory.GetFiles(destdir);
//------比较两目录中的文件信息(本层目录)--------------
foreach (string sfilename in SFiles)
{
&