public async static Task Update(Package package, Validator val, PackageOverview overview) { //Create tmp dir so files are gone after execution. using (TmpDir dir = new TmpDir(".")) using (WebClient client = new WebClient()) { //Check if it exists if (PackageUtil.DoesPackageExist(package)) { string filename = Path.GetFileName(package.downloadLocation); Console.WriteLine("Getting newest version of package " + package.name); //Setup loading bar client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(LoadingBar.DownloadProgressCallback); //Get latest version await client.DownloadFileTaskAsync(package.downloadLink, dir.dirName + filename); Console.Write("\n\r"); //Compare. The && ! will make it so that it will always go to 2nd case if val.forceUpdate is ture. if (FileCompare.CompareFiles(dir.dirName + filename, "../sm_plugins/" + package.downloadLocation) && !val.forceUpdate) { Console.WriteLine(package.name + " is up to date."); } else { File.Move(dir.dirName + filename, "../sm_plugins/" + package.downloadLocation, true); Console.WriteLine(package.name + " was updated."); } } else { Console.WriteLine(("WARNING: Package " + package.name + " is not installed. Skipping.").Pastel("ffff00")); } } }
public void ValidatedGames() { string streamingAssetsPath = Path.Combine(Application.dataPath, "StreamingAssets"); foreach (string directory in Directory.EnumerateDirectories(streamingAssetsPath)) { string fileName = Path.GetFileName(directory); string name = fileName.Substring(0, fileName.IndexOf('@')); if ("Standard Playing Cards".Equals(name)) { name = "Standard"; } var streamingDirectoryInfo = new DirectoryInfo(directory); var docsDirectoryInfo = new DirectoryInfo( Application.dataPath.Remove(Application.dataPath.Length - 6, 6) + $"docs/games/{name}"); IEnumerable <FileInfo> streamingFiles = streamingDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories) .Where(file => !file.Name.EndsWith(UnityFileMethods.MetaExtension) && !file.Name.Contains("Standard Playing Cards.json")); IEnumerable <FileInfo> docsFiles = docsDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories); // A custom file comparer defined below var fileCompare = new FileCompare(); IEnumerable <FileInfo> missingFiles = (from file in streamingFiles select file).Except(docsFiles, fileCompare); Assert.IsEmpty(missingFiles); } }
public async Task TestCancellation() { var bytes = new byte[StreamCompare.DefaultBufferSize]; var path1 = Path.GetRandomFileName(); var path2 = Path.GetRandomFileName(); using (var file1 = File.Create(path1)) using (var file2 = File.Create(path2)) { var tasks = new[] { file1.WriteAsync(bytes), file2.WriteAsync(bytes), }; await Task.WhenAll(tasks.Select(t => t.AsTask())); } var fcompare = new FileCompare(); var canceled = new CancellationToken(true); await Assert.ThrowsExceptionAsync <TaskCanceledException>(async() => { await fcompare.AreEqualAsync(path1, path2, canceled); }); File.Delete(path1); File.Delete(path2); }
public async Task CompareIdenticalFiles() { var rng = new Random(); var path1 = Path.GetRandomFileName(); var path2 = Path.GetRandomFileName(); using (var file1 = File.Create(path1)) using (var file2 = File.Create(path2)) { var bytes = new byte[FileSize]; rng.NextBytes(bytes); var tasks = new[] { file1.WriteAsync(bytes), file2.WriteAsync(bytes), }; await Task.WhenAll(tasks.Select(t => t.AsTask())); } var fcompare = new FileCompare(); Assert.IsTrue(await fcompare.AreEqualAsync(path1, path2)); File.Delete(path1); File.Delete(path2); }
/// <summary> /// 如何比较两个文件夹的内容 /// </summary> static void CompareDirs() { // Create two identical or different temporary folders // on a local drive and change these file paths. string pathA = @"C:\TestDir"; string pathB = @"C:\TestDir2"; System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA); System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB); // Take a snapshot of the file system. IEnumerable <System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories); IEnumerable <System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories); //A custom file comparer defined below FileCompare myFileCompare = new FileCompare(); // This query determines whether the two folders contain // identical file lists, based on the custom file comparer // that is defined in the FileCompare class. // The query executes immediately because it returns a bool. bool areIdentical = list1.SequenceEqual(list2, myFileCompare); if (areIdentical == true) { Console.WriteLine("the two folders are the same"); } else { Console.WriteLine("The two folders are not the same"); } // Find the common files. It produces a sequence and doesn't // execute until the foreach statement. var queryCommonFiles = list1.Intersect(list2, myFileCompare); if (queryCommonFiles.Any()) { Console.WriteLine("The following files are in both folders:"); foreach (var v in queryCommonFiles) { Console.WriteLine(v.FullName); //shows which items end up in result list } } else { Console.WriteLine("There are no common files in the two folders."); } // Find the set difference between the two folders. // For this example we only check one way. var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare); Console.WriteLine("The following files are in list1 but not list2:"); foreach (var v in queryList1Only) { Console.WriteLine(v.FullName); } }
static void Main(string[] args) { //Create two new folders to be compared string pathA = @"T:\Purchasing\101-00071 GRN's"; string pathB = @"T:\Purchasing\101-00071 GRN's\Inkron"; System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(pathA); System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(pathB); // Read file names and write to lists. IEnumerable <System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories); IEnumerable <System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories); //Compare file function FileCompare myFileCompare = new FileCompare(); // Find the entries that differ between the two folders. var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare); Console.WriteLine("The following files are in list1 but not list2:"); foreach (var v in queryList1Only) { Console.WriteLine(v.FullName); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public void CompareTwoFolders() { System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(_pathA); System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(_pathB); // Interface to take snapshot of files IEnumerable <System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories); IEnumerable <System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories); FileCompare myFileCompare = new FileCompare(); // determines whether the two folders contain identical file list based on // custom file comparer class below bool areIdentical = list1.SequenceEqual(list2, myFileCompare); if (areIdentical == true) { Console.WriteLine("the two folders are the same"); } else { Console.WriteLine("The two folders are not the same"); } // Find the common files. It produces a sequnece a sequence and doesn't execute // until the foreach statement. var queryCommonFiles = list1.Intersect(list2, myFileCompare); var commonFiles = queryCommonFiles.ToList(); if (commonFiles.Any()) { Console.WriteLine("The following files are in both folders:"); foreach (var v in commonFiles) { Console.WriteLine(v.FullName); //shows which items end up in result list } } else { Console.WriteLine("There are no common files in the two folders."); } // Find the set difference between the two folders. // For this example we only check one way. var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare); Console.WriteLine("The following files are in list1 but not list2:"); foreach (var v in queryList1Only) { Console.WriteLine(v.FullName); } // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
public void FileCompareInit() { // With the default buffer size var fcompare = new FileCompare(); // With a custom buffer size fcompare = new FileCompare((uint)(StreamCompare.DefaultBufferSize / 7)); }
internal static void ShowFileCompare(Form form) { FileCompare fileCompare = new FileCompare { Owner = form }; fileCompare.InitializeForm(); fileCompare.ShowDialog(form); }
//This method update the state.json file with current information public void UpdateState(string name, bool isDone, string src, string dest) { //here we get some information for the file var date = DateTime.Now; string hours = "" + date.Hour + " H " + date.Minute + " M"; string state = "not active"; int totalFiles = 0; long totalSize = 0; int progress = 0; int reminingFiles = 0; int sizeRemainingFiles = 0; //if the save is in progress, we need some more data about progress if (!isDone) { /*here we get the two directory and all their files * in a format that allows us to extract information from them */ DirectoryInfo dir1 = new DirectoryInfo(src); DirectoryInfo dir2 = new DirectoryInfo(dest); IEnumerable <FileInfo> files1 = dir1.GetFiles("*.*", SearchOption.AllDirectories); IEnumerable <FileInfo> files2 = dir2.GetFiles("*.*", SearchOption.AllDirectories); FileCompare fileCompare = new FileCompare(); IEnumerable <FileInfo> queryList2Only = files1.Except(files2, fileCompare); //information about directory to save, total of files and total length foreach (FileInfo sFile in files1) { totalFiles++; totalSize += (long)sFile.Length; } //information about files that need to be saved foreach (FileInfo sFile in queryList2Only) { reminingFiles++; sizeRemainingFiles += (int)sFile.Length; } progress = ((totalFiles - reminingFiles) * 100) / totalFiles; state = "active"; } //all these information are export to json file this.CreateState(hours, name, state, totalFiles, totalSize, progress, reminingFiles, sizeRemainingFiles, src, dest); }
internal static void CompareTabText(FileCompare form, String[] itemValues) { Form1 form1 = (Form1)form.Owner; XtraTabControl pagesTabControl = form1.pagesTabControl; ListBox tabPagesListBox = form.tabPagesListBox; CheckBox caseSensitiveCheckBox = form.caseSensitiveCheckBox; if (tabPagesListBox.SelectedIndices.Count != 2) { throw new TabException(LanguageUtil.GetCurrentLanguageString("ErrorCompare", className)); } String[] selectedTabNames = new String[tabPagesListBox.SelectedIndices.Count]; for (int i = 0; i < tabPagesListBox.SelectedIndices.Count; i++) { selectedTabNames[i] = itemValues[tabPagesListBox.SelectedIndices[i]]; } XtraTabPage tabPage1 = GetXtraTabPageFromName(pagesTabControl, selectedTabNames[0]); XtraTabPage tabPage2 = GetXtraTabPageFromName(pagesTabControl, selectedTabNames[1]); CustomRichTextBox pageTextBox1 = ProgramUtil.GetPageTextBox(tabPage1); CustomRichTextBox pageTextBox2 = ProgramUtil.GetPageTextBox(tabPage2); String text1 = pageTextBox1.Text; String text2 = pageTextBox2.Text; if (!caseSensitiveCheckBox.Checked) { text1 = text1.ToLower(); text2 = text2.ToLower(); } if (text1 == text2) { WindowManager.ShowInfoBox(form1, LanguageUtil.GetCurrentLanguageString("TabEquals", className)); } else if (text1.Replace(ConstantUtil.newLine, String.Empty) == text2.Replace(ConstantUtil.newLine, String.Empty)) { WindowManager.ShowAlertBox(form1, LanguageUtil.GetCurrentLanguageString("TabAlmostEquals_Returns", className)); } else if (text1.Replace(" ", String.Empty).Replace("\t", String.Empty) == text2.Replace(" ", String.Empty).Replace("\t", String.Empty)) { WindowManager.ShowAlertBox(form1, LanguageUtil.GetCurrentLanguageString("TabAlmostEquals_Spaces", className)); } else if (text1.Replace(ConstantUtil.newLine, String.Empty).Replace(" ", String.Empty).Replace("\t", String.Empty) == text2.Replace(ConstantUtil.newLine, String.Empty).Replace(" ", String.Empty).Replace("\t", String.Empty)) { WindowManager.ShowAlertBox(form1, LanguageUtil.GetCurrentLanguageString("TabAlmostEquals_ReturnsAndSpaces", className)); } else { WindowManager.ShowAlertBox(form1, LanguageUtil.GetCurrentLanguageString("TabDifferents", className)); } }
/// <summary> /// 对比两个路径下的文件获取差异文件路径 /// </summary> /// <param name="path1"></param> /// <param name="path2"></param> /// <param name="list1Only"></param> private static void FolderFileCompare(string path1, string path2, ref List <string> list1Only) { List <FileInfo> list1 = GetFiles(path1, "*.lua"); List <FileInfo> list2 = GetFiles(path2, "*.lua"); FileCompare fileCompare = new FileCompare(); var queryList1Only = (from file in list1 select file).Except(list2, fileCompare); foreach (var v in queryList1Only) { list1Only.Add(v.FullName); } }
public IEnumerable <string> GetConfilctedFiles(string src, string dest) { DirectoryInfo dir1 = new DirectoryInfo(src); DirectoryInfo dir2 = new DirectoryInfo(dest); IEnumerable <FileInfo> list1 = dir1.GetFiles("*.*", SearchOption.AllDirectories); IEnumerable <FileInfo> list2 = dir2.GetFiles("*.*", SearchOption.AllDirectories); FileCompare myFileCompare = new FileCompare(); var queryCommonFiles = list1.Intersect(list2, myFileCompare); return(queryCommonFiles.Select(m => m.FullName)); }
static void Main(string[] args) { string dataPath = @"./data/"; if (args.Length > 0) { dataPath = args[0]; } FileCompare fileCom = new FileCompare(); fileCom.CompareFile(dataPath, @"./md5"); }
public static bool CompareFolders(string pathA, string pathB) { DirectoryInfo dirA = null; DirectoryInfo dirB = null; try { dirA = new DirectoryInfo(pathA); dirB = new DirectoryInfo(pathB); } catch (Exception ex) { logger.Error(ex, $"DirectoryInfo error."); return(false); } if (dirA.Exists == false || dirB.Exists == false) { return(false); } IEnumerable <FileInfo> dirAFiles = null; IEnumerable <FileInfo> dirBFiles = null; try { dirAFiles = dirA.GetFiles("*.*", SearchOption.AllDirectories); dirBFiles = dirB.GetFiles("*.*", SearchOption.AllDirectories); } catch (Exception ex) { logger.Error(ex, $"GetFiles error."); return(false); } FileCompare myFileCompare = new FileCompare(); bool areIdentical = dirAFiles.SequenceEqual(dirBFiles, myFileCompare); if (areIdentical == true) { return(true); } else { return(false); } }
public List <string> GetPersonsList() { pathList.Clear(); FileInfo[] infos = FileHelper.GetFileList(PersonDataPath, "*.bin"); FileCompare fileCompare = new FileCompare(); if (infos != null) { Array.Sort(infos, fileCompare); for (int i = 0; i < infos.Length; i++) { string[] lst = infos[i].Name.Split('.'); pathList.Add(lst[0]); } } return(pathList); }
/// <summary> /// 比较两个文件夹差异 /// </summary> /// <param name="folder1"></param> /// <param name="folder2"></param> public static void CompareDirs(string folder1, string folder2) { int folder1Length = folder1.Length; int folder2Length = folder2.Length; DirectoryInfo dir1 = new DirectoryInfo(folder1); DirectoryInfo dir2 = new DirectoryInfo(folder2); IEnumerable <FileInfo> fileList1 = dir1.GetFiles("*.*", SearchOption.AllDirectories); IEnumerable <FileInfo> fileList2 = dir2.GetFiles("*.*", SearchOption.AllDirectories); FileCompare myFileCompare = new FileCompare(); bool areIdentical = fileList1.SequenceEqual(fileList2, myFileCompare); if (areIdentical) { Console.WriteLine("两个文件夹内容一致"); } else { Console.WriteLine("两个文件夹内容不一致"); } var queryCommonFiles = fileList1.Intersect(fileList2, myFileCompare); if (queryCommonFiles.Any()) { Console.WriteLine("以下文件是两个文件夹共有的:"); foreach (var fi in queryCommonFiles) { Console.WriteLine($"{fi.FullName.Substring(folder1Length)}"); } } else { Console.WriteLine("两个文件夹没有相同文件"); } var queryList1Only = fileList1.Except(fileList2, myFileCompare); Console.WriteLine("以下文件是folder1有而folder2没有的"); foreach (var v in queryList1Only) { Console.WriteLine(v.FullName.Substring(folder1Length)); } }
private int RemoveFiles(string p_source, string p_target) { var _result = 0; var _filesA = Directory.EnumerateFiles(p_source, "*.*", SearchOption.TopDirectoryOnly) .Where(f => ContainsFile(__config.SourceExcludeFiles, f) == false) .ToList(); var _filesB = Directory.EnumerateFiles(p_target, "*.*", SearchOption.TopDirectoryOnly) .Where(f => ContainsFile(__config.TargetExcludeFiles, f) == false) .ToList(); var _file_compare = new FileCompare(__config.Offset); var _filesB_only = (from _file in _filesB select _file.ToLower()).Except(_filesA, _file_compare); foreach (var _f in _filesB_only) { if (__config.RemoveFiles == true) { try { File.SetAttributes(_f, FileAttributes.Normal); File.Delete(_f); Console.WriteLine("-'{0}': {1}", ++__config.DeletedFile, _f); } catch (Exception) { Console.WriteLine("-'{0}': {1}", ++__config.UnDeletedFile, _f); } } else { Console.WriteLine("-'{0}': {1}", ++__config.UnDeletedFile, _f); } _result++; } return _result; }
public void TextFileCompare() { // get this assembly file var assemblyFile = Assembly.GetExecutingAssembly().Location; Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual(assemblyFile, assemblyFile)); Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual("FileOne.txt", "FileOne.txt")); Assert.AreEqual(FileCompare.Result.Identical, FileCompare.AreEqual("FileOne.txt", "FileTwo.txt")); Assert.AreEqual(FileCompare.Result.Different, FileCompare.AreEqual("FileOne.txt", assemblyFile)); Assert.AreEqual(FileCompare.Result.File2Missing, FileCompare.AreEqual("FileOne.txt", "xxx")); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual("xxx", "FileOne.txt")); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "yyy")); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "xxx")); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual(null, "FileOne.txt")); int bufSize = 4096; Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual(assemblyFile, assemblyFile, bufSize)); Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual("FileOne.txt", "FileOne.txt", bufSize)); Assert.AreEqual(FileCompare.Result.Identical, FileCompare.AreEqual("FileOne.txt", "FileTwo.txt", bufSize)); Assert.AreEqual(FileCompare.Result.Different, FileCompare.AreEqual("FileOne.txt", assemblyFile, bufSize)); Assert.AreEqual(FileCompare.Result.File2Missing, FileCompare.AreEqual("FileOne.txt", "xxx", bufSize)); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual("xxx", "FileOne.txt", bufSize)); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "yyy", bufSize)); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "xxx", bufSize)); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual(null, "FileOne.txt", bufSize)); var buffer = new byte[8192]; var b1 = buffer.AsSpan(0, 4096); var b2 = buffer.AsSpan(4096); Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual(assemblyFile, assemblyFile, b1, b2)); Assert.AreEqual(FileCompare.Result.SameFile, FileCompare.AreEqual("FileOne.txt", "FileOne.txt", b1, b2)); Assert.AreEqual(FileCompare.Result.Identical, FileCompare.AreEqual("FileOne.txt", "FileTwo.txt", b1, b2)); Assert.AreEqual(FileCompare.Result.Different, FileCompare.AreEqual("FileOne.txt", assemblyFile, b1, b2)); Assert.AreEqual(FileCompare.Result.File2Missing, FileCompare.AreEqual("FileOne.txt", "xxx", b1, b2)); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual("xxx", "FileOne.txt", b1, b2)); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "yyy", b1, b2)); Assert.AreEqual(FileCompare.Result.BothFilesMissing, FileCompare.AreEqual("xxx", "xxx", b1, b2)); Assert.AreEqual(FileCompare.Result.File1Missing, FileCompare.AreEqual(null, "FileOne.txt", b1, b2)); }
//Method checks to see if file is same to other directory files private bool IsContentSame(string file1, string file2) { bool isContentSame = false; if (Directory.Exists(file1) && Directory.Exists(file2)) { DirectoryInfo dir1 = new DirectoryInfo(file1); DirectoryInfo dir2 = new DirectoryInfo(file2); IEnumerable <FileInfo> list1 = dir1.GetFiles("*.*", SearchOption.AllDirectories); IEnumerable <FileInfo> list2 = dir2.GetFiles("*.*", SearchOption.AllDirectories); FileCompare myFileCompare = new FileCompare(); isContentSame = list1.SequenceEqual(list2, myFileCompare); } else if (Path.HasExtension(file1)) { using (var md5 = MD5.Create()) { byte[] a, b; using (var stream = File.OpenRead(file1)) { a = md5.ComputeHash(stream); } using (var stream = File.OpenRead(file2)) { b = md5.ComputeHash(stream); } isContentSame = Encoding.UTF8.GetString(a) == Encoding.UTF8.GetString(b); } } return(isContentSame); }
public Dictionary<string, string> GetNewFiles() { try { DirectoryInfo dir1 = new DirectoryInfo(NewVersionPathRoot); DirectoryInfo dir2 = new DirectoryInfo(OldVersionPathRoot); IEnumerable<FileSystemInfo> list1 = dir1.GetFileSystemInfos("*", SearchOption.AllDirectories); IEnumerable<FileSystemInfo> list2 = dir2.GetFileSystemInfos("*", SearchOption.AllDirectories); var oldSet = new HashSet<string>(list2.Select(dir => dir.FullName.Replace(OldVersionPathRoot, ""))); var newSet = list1.Where(dir => !oldSet.Contains(dir.FullName.Replace(NewVersionPathRoot, ""))); Dictionary<string, string> hs = new Dictionary<string, string>(); foreach (var v in newSet) { hs.Add(v.FullName, v.Extension); } IEnumerable<FileInfo> list3 = dir1.GetFiles("*", SearchOption.AllDirectories); IEnumerable<FileInfo> list4 = dir2.GetFiles("*", SearchOption.AllDirectories); FileCompare fCompare = new FileCompare(); var queryList1Only = (from file in list3 select file).Except(list4, fCompare); foreach (var v in queryList1Only) { if (!hs.Keys.Contains(v.FullName)) { hs.Add(v.FullName, v.Extension); } } RemoveFiles(hs); hs.OrderBy(v => v.Key); return hs; } catch (Exception ex) { throw ex; } }
public async Task BasicFileCompare() { var path1 = Path.GetRandomFileName(); var path2 = Path.GetRandomFileName(); using (var file1 = File.Create(path1)) using (var file2 = File.Create(path2)) { var bytes1 = new byte[FileSize]; var bytes2 = new byte[FileSize]; var rng = new Random(); rng.NextBytes(bytes1); rng.NextBytes(bytes2); var tasks = new[] { file1.WriteAsync(bytes1), file2.WriteAsync(bytes2), }; await Task.WhenAll(tasks.Select(t => t.AsTask())); } var fileInfo1 = new FileInfo(path1); var fileInfo2 = new FileInfo(path2); Assert.AreEqual(FileSize, fileInfo1.Length); Assert.AreEqual(FileSize, fileInfo2.Length); var fcompare = new FileCompare(); Assert.IsFalse(await fcompare.AreEqualAsync(path1, path2)); // These will throw if the handles haven't been closed, which would indicate a bug File.Delete(path1); File.Delete(path2); }
public async Task CompareSameFile() { var rng = new Random(); var path1 = Path.GetRandomFileName(); using (var file1 = File.Create(path1)) { var bytes1 = new byte[FileSize]; rng.NextBytes(bytes1); await file1.WriteAsync(bytes1); } var fileInfo1 = new FileInfo(path1); Assert.AreEqual(FileSize, fileInfo1.Length); var fcompare = new FileCompare(); Assert.IsTrue(await fcompare.AreEqualAsync(path1, path1)); File.Delete(path1); }
public static bool MatchDirectoryContents(string sourcePath, string destinationPath) { FileCompare fileCompare = new FileCompare(); DirectoryInfo srcDir = new DirectoryInfo(sourcePath); DirectoryInfo destDir = new DirectoryInfo(destinationPath); FileInfo[] lstSrcFiles = srcDir.GetFiles(); FileInfo[] lstDestFiles = destDir.GetFiles(); DirectoryInfo[] srcSubDirs = srcDir.GetDirectories(); DirectoryInfo[] destSubDirs = destDir.GetDirectories(); if (fileCompare.Equals(lstSrcFiles, lstDestFiles)) { if (srcSubDirs.Count() == 0 && destSubDirs.Count() == 0) { return(true); } else if (srcSubDirs.Count() == destSubDirs.Count()) { bool result = false; for (int i = 0; i < srcSubDirs.Count(); i++) { result = MatchDirectoryContents(srcSubDirs[i].FullName, destSubDirs[i].FullName); } return(result); } else { return(false); } } else { return(false); } }
public async Task CompareDifferentLengths() { var bytes = new byte[StreamCompare.DefaultBufferSize * 2]; var path1 = Path.GetRandomFileName(); var path2 = Path.GetRandomFileName(); using (var file1 = File.Create(path1)) using (var file2 = File.Create(path2)) { var tasks = new[] { file1.WriteAsync(bytes), file2.WriteAsync(bytes.AsMemory(12)) }; await Task.WhenAll(tasks.Select(t => t.AsTask())); } // And use a custom buffer size var fcompare = new FileCompare(3907); // prime number for good measure Assert.IsFalse(await fcompare.AreEqualAsync(path1, path2)); }
private void btnSync_Click(object sender, EventArgs e) { //Apply addler32 to files, if the same equal their last write timestamp //CATCH the mp3 headers might vary, even when content is the same; choose to ignore if filesize is the same var allDiffs = differences.Where( x => x.DifferenceType == DiffType.LastWritten && x.ItemType == ItemType.File && !x.Source.Extension.ToUpper().Equals(".MP3") ); foreach (var diff in allDiffs) { FileCompare compare = new FileCompare(); if (compare.ExternalCompareByHash(diff.Source as FileInfo, diff.Destination as FileInfo)) { diff.Destination.LastWriteTimeUtc = diff.Source.LastWriteTimeUtc; } } }
/// <summary> /// This is the base copy/move function that I call when timing is not important. For me this would only run /// on our main network, and not at any facility site, but it would be really great for things like large /// path restores which will take a long time, and can function in a fire and forget kind of way. /// In all honestly the need for something like this is minuscule, since robocopy exists and it is much easier to implement /// But this would allow for easier use for end users, and in the end I wanted my app to be able to do both; /// Be a timer move/copy and a standard move/copy, so we can call a single app up to do multiple things. /// </summary> public async Task RunCopyorMove(String StartDirectory, String EndDirectory, PauseToken _pts, CancellationToken token, string logfile, int filesSkipped, int filesCopied, bool isRunning, long sum, long endsum, long progressvalue, long progressum) { if (!Alphaleonis.Win32.Filesystem.Directory.Exists(EndDirectory)) { Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(EndDirectory); } if (!Alphaleonis.Win32.Filesystem.Directory.Exists(logfile)) { Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(logfile); } List <String> FileNames = new List <String>(); List <String> SkippedFiles = new List <String>(); List <String> ExtraFiles = new List <String>(); Alphaleonis.Win32.Filesystem.DirectoryInfo SrcDirct = new Alphaleonis.Win32.Filesystem.DirectoryInfo(StartDirectory); Alphaleonis.Win32.Filesystem.DirectoryInfo DestDirct = new Alphaleonis.Win32.Filesystem.DirectoryInfo(EndDirectory); IEnumerable <Alphaleonis.Win32.Filesystem.FileInfo> srclist = SrcDirct.EnumerateFiles("*", SearchOption.AllDirectories); IEnumerable <Alphaleonis.Win32.Filesystem.FileInfo> destlist = DestDirct.EnumerateFiles("*", SearchOption.AllDirectories); FileCompare myCompare = new FileCompare(); var destListOnly = (from file in destlist select file).Except(srclist, myCompare); var destListLen = destlist.Intersect(srclist, myCompare); var srcListOnly = (from file in srclist select file).Except(destlist, myCompare); try { ///This warning is nice to have so the user does not accidentally do a move and not realize until it is too late. ///This could possibly be a message-box if you are really concered. if (checkBox2.Checked) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("This will delete the source path. If you did not intend that please hit Stop Copy"); listBox1.TopIndex = listBox1.Items.Count - 1; }); } var filecompare = Task.Run(async() => { this.Invoke((MethodInvoker) delegate { label7.Text = "Getting Files Please wait"; listBox1.TopIndex = listBox1.Items.Count - 1; }); if (_pts.IsPaused) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Paused"); listBox1.TopIndex = listBox1.Items.Count - 1; }); } else { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Not paused"); listBox1.TopIndex = listBox1.Items.Count - 1; }); } foreach (var v in destListOnly) { await _pts.WaitWhilePausedAsync(); extraFiles++; this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Extra File " + v.FullName); listBox1.TopIndex = listBox1.Items.Count - 1; }); ExtraFiles.Add(v.FullName); } foreach (var v in srcListOnly) { await _pts.WaitWhilePausedAsync(); sum += v.Length; } foreach (var v in destListLen) { await _pts.WaitWhilePausedAsync(); filesSkipped++; files--; this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Skipped File " + v.FullName); listBox1.TopIndex = listBox1.Items.Count - 1; }); SkippedFiles.Add(v.FullName); sum += v.Length; } this.Invoke((MethodInvoker) delegate { label5.Text = "Files Skipped " + filesSkipped + " Extra Files " + extraFiles; }); }); await filecompare; ///Get the total number of files, and their size. Do note this will take a really long time. ///Which is why I left it off the After6 run, because those are usually very large moves. ///If you are talking 100s of gigs or even coming close to TB, it would eclipse the timers ///trying to get the info. var amountcopied = Task.Run(() => { var existingFiles = Alphaleonis.Win32.Filesystem.Directory.GetFiles(EndDirectory, "*", SearchOption.AllDirectories); var existingRoot = Alphaleonis.Win32.Filesystem.Directory.GetFiles(EndDirectory); files += Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory, "*", SearchOption.AllDirectories).Count(); while (isRunning == true) { float secelasped = ((float)sw.ElapsedMilliseconds / 1000); float secleft = (int)Math.Ceiling((secelasped / endsum) * (sum - endsum)); TimeSpan lefttime = TimeSpan.FromSeconds(secleft); if (sum > Int32.MaxValue) { progressum = sum / 1024; progressvalue = endsum / 1024; } else { progressum = sum; progressvalue = endsum; } if (endsum > Int32.MaxValue) { progressvalue = endsum / 1024; progressum = sum / 1024; } else { progressum = sum; progressvalue = endsum; } this.Invoke((MethodInvoker) delegate { progressBar1.Style = System.Windows.Forms.ProgressBarStyle.Continuous; progressBar1.Minimum = 0; progressBar1.Maximum = Convert.ToInt32(progressum); progressBar1.Value = Convert.ToInt32(progressvalue); label9.Text = "Speed: " + (endsum / 1024d / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00") + " mb/s"; if (sum > 1024 && sum < 1048576) { label6.Text = "Amount copied " + ((endsum / 1024d)).ToString("0.00") + "/" + ((sum / 1024d)).ToString("0.00") + " KB"; } else if (sum > 1048576 && sum < 1073741824) { label6.Text = "Amount copied " + ((endsum / 1024d) / 1024d).ToString("0.00") + "/" + ((sum / 1024d) / 1024d).ToString("0.00") + " MB"; } else if (sum > 1073741824) { label6.Text = "Amount copied " + (((endsum / 1024d) / 1024d) / 1024d).ToString("0.00") + "/" + (((sum / 1024d) / 1024d) / 1024d).ToString("0.00") + " GB"; } label4.Text = "Files to Copy " + (files - filesCopied) + " Files Copied " + (filesCopied); //label10.Text = "Files Copied " + (filesCopied); label8.Text = "Time Remaning " + lefttime.ToString(); label7.Text = "Percent done " + ((100 * endsum / sum)).ToString() + "%"; }); } if (isRunning == false) { this.Invoke((MethodInvoker) delegate { label7.Text = ""; }); } }); var moveTask = Task.Run(async() => { sw.Start(); ///Note, this only works for sub directories, and will not copy over root contents, the next foreach loop takes care of that. ///This is also wrapped in the same task, so it will do the sub first, then the root, and run it both on the same thread. foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(StartDirectory, "*", SearchOption.AllDirectories)) { ///I initially did this with a DirectoryInfo and Alphaleonis.Win32.Filesystem.FileInfo, inplace of the style I did now. But this had a weird outcome ///Where a subdir folder would be created, but the files would be copied to root. Doing it this way works Alphaleonis.Win32.Filesystem.Directory.CreateDirectory(dirPath.Replace(StartDirectory, EndDirectory)); foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(dirPath)) { try { using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(filename.Replace(StartDirectory, EndDirectory), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { await _pts.WaitWhilePausedAsync(); string source = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle); string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle); ///Check if the length match (since the file is created above) ///If the length is not right, it restarts the copy (meaning if stopped in the middle of copying it will ///start at the beginning rather than the same byte [TODO: Make it start the previous byte]) ///Else it closes the current stream, and displays it already exists. Because of the foreach ///It will recursively start a new stream with the next file if (Alphaleonis.Win32.Filesystem.File.Exists(destination) && DestinationStream.Length == SourceStream.Length) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Skipping files. Please wait"); listBox1.TopIndex = listBox1.Items.Count - 1; }); //filesSkipped++; //files--; endsum += DestinationStream.Length; //SkippedFiles.Add(destination); DestinationStream.Close(); SourceStream.Close(); } else if (Alphaleonis.Win32.Filesystem.File.Exists(source) && DestinationStream.Length != SourceStream.Length) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Starting Copy of " + source); listBox1.TopIndex = listBox1.Items.Count - 1; }); await SourceStream.CopyToAsync(DestinationStream, 262144, token); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Finished Copying " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); filesCopied++; FileNames.Add(destination); endsum += DestinationStream.Length; } token.ThrowIfCancellationRequested(); } } } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("File move (subdir) date caused it"); }); throw; } } } foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory)) { try { using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(EndDirectory + filename.Substring(filename.LastIndexOf('\\')), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { await _pts.WaitWhilePausedAsync(); string source = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle); string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle); if (Alphaleonis.Win32.Filesystem.File.Exists(destination) && DestinationStream.Length == SourceStream.Length) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Skipping files. Please wait"); listBox1.TopIndex = listBox1.Items.Count - 1; }); //filesSkipped++; //files--; endsum += DestinationStream.Length; //SkippedFiles.Add(destination); DestinationStream.Close(); SourceStream.Close(); } else if (Alphaleonis.Win32.Filesystem.File.Exists(source) && DestinationStream.Length != SourceStream.Length) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Starting Copy of " + source); listBox1.TopIndex = listBox1.Items.Count - 1; }); await SourceStream.CopyToAsync(DestinationStream, 262144, token); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Finished Copying " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); filesCopied++; FileNames.Add(destination); endsum += DestinationStream.Length; } token.ThrowIfCancellationRequested(); } } } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("File move (rootdir) date caused it"); listBox1.TopIndex = listBox1.Items.Count - 1; }); throw; } } }); await moveTask; var modify = Task.Run(async() => { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Setting modify and change date. Please wait"); listBox1.TopIndex = listBox1.Items.Count - 1; }); foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(StartDirectory)) { try { using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(EndDirectory + filename.Substring(filename.LastIndexOf('\\')), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { await _pts.WaitWhilePausedAsync(); string source = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle); string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Changing Modify, Creation, and Change date for " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); DateTime dt = Alphaleonis.Win32.Filesystem.File.GetCreationTime(source); DateTime at = Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(source); DateTime wt = Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(source); Alphaleonis.Win32.Filesystem.File.SetCreationTime(destination, dt); Alphaleonis.Win32.Filesystem.File.SetLastAccessTime(destination, at); Alphaleonis.Win32.Filesystem.File.SetLastWriteTime(destination, wt); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Modify, Creation, and Change date set for " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); } } } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("File modify date caused it"); listBox1.TopIndex = listBox1.Items.Count - 1; }); throw; } } foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(StartDirectory, "*", SearchOption.AllDirectories)) { foreach (string filename in Alphaleonis.Win32.Filesystem.Directory.EnumerateFiles(dirPath)) { try { using (FileStream SourceStream = Alphaleonis.Win32.Filesystem.File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { using (FileStream DestinationStream = Alphaleonis.Win32.Filesystem.File.Open(filename.Replace(StartDirectory, EndDirectory), FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { await _pts.WaitWhilePausedAsync(); string source = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(SourceStream.SafeFileHandle); string destination = Alphaleonis.Win32.Filesystem.Path.GetFinalPathNameByHandle(DestinationStream.SafeFileHandle); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Changing Modify, Creation, and Change date for " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); DateTime dt = Alphaleonis.Win32.Filesystem.File.GetCreationTime(source); DateTime at = Alphaleonis.Win32.Filesystem.File.GetLastAccessTime(source); DateTime wt = Alphaleonis.Win32.Filesystem.File.GetLastWriteTime(source); Alphaleonis.Win32.Filesystem.File.SetCreationTime(destination, dt); Alphaleonis.Win32.Filesystem.File.SetLastAccessTime(destination, at); Alphaleonis.Win32.Filesystem.File.SetLastWriteTime(destination, wt); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Modify, Creation, and Change date set for " + destination); listBox1.TopIndex = listBox1.Items.Count - 1; }); } } } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("File modify date caused it"); listBox1.TopIndex = listBox1.Items.Count - 1; }); throw; } } } DateTime dirt = new DateTime(); DateTime dira = new DateTime(); DateTime dirw = new DateTime(); foreach (string dirPath in Alphaleonis.Win32.Filesystem.Directory.GetDirectories(StartDirectory, "*", SearchOption.AllDirectories)) { dirt = Alphaleonis.Win32.Filesystem.Directory.GetCreationTime(dirPath); dira = Alphaleonis.Win32.Filesystem.Directory.GetLastAccessTime(dirPath); dirw = Alphaleonis.Win32.Filesystem.Directory.GetLastWriteTime(dirPath); } foreach (string endDirPath in Alphaleonis.Win32.Filesystem.Directory.EnumerateDirectories(EndDirectory, "*", SearchOption.AllDirectories)) { try { await _pts.WaitWhilePausedAsync(); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Changing Modify, Creation, and Change date for " + endDirPath); listBox1.TopIndex = listBox1.Items.Count - 1; }); Alphaleonis.Win32.Filesystem.Directory.SetCreationTime(endDirPath, dirt); Alphaleonis.Win32.Filesystem.Directory.SetLastAccessTime(endDirPath, dira); Alphaleonis.Win32.Filesystem.Directory.SetLastWriteTime(endDirPath, dirw); this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Modify, Creation, and Change date set for " + endDirPath); listBox1.TopIndex = listBox1.Items.Count - 1; }); } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("Directory modify date caused it"); listBox1.TopIndex = listBox1.Items.Count - 1; }); throw; } } }); await modify; if (checkBox2.Checked) { if (Alphaleonis.Win32.Filesystem.Directory.Exists(SrcPath.Text)) { try { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Deleting the source directory, please wait."); listBox1.TopIndex = listBox1.Items.Count - 1; }); var folderdelete = Task.Run(async() => { Alphaleonis.Win32.Filesystem.Directory.Delete(SrcPath.Text, true); }, token); await folderdelete; } catch (System.IO.IOException ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); listBox1.Items.Add("Folder Delete caused it"); listBox1.TopIndex = listBox1.Items.Count - 1; }); throw; } } this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("**********File Move has Completed!*****"); listBox1.TopIndex = listBox1.Items.Count - 1; }); PrepareControlsForCancel(); } else { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("**********File Copy has Completed!*****"); listBox1.TopIndex = listBox1.Items.Count - 1; }); PrepareControlsForCancel(); } } catch (OperationCanceledException) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add("Cancelled."); listBox1.TopIndex = listBox1.Items.Count - 1; }); PrepareControlsForCancel(); } catch (Exception ex) { this.Invoke((MethodInvoker) delegate { listBox1.Items.Add(ex); }); ErrorLog(ex, logfile, StartDirectory); } FileLog(StartDirectory, logfile, FileNames, SkippedFiles, filesCopied, endsum, filesSkipped, extraFiles, ExtraFiles); }
public async Task CheckOnStart() { bool areIdentical = true; IEnumerable<DirectoryInfo> dstDirs = new List<DirectoryInfo>(); await Task.Factory.StartNew(() => { DirectoryInfo source = new DirectoryInfo(_source); IEnumerable<DirectoryInfo> srcDirs = source.GetDirectories(); DirectoryInfo destination = new DirectoryInfo(_destination); dstDirs = destination.GetDirectories(); FileCompare myFileCompare = new FileCompare(); IEnumerable<FileInfo> sourceList = source.GetFiles("*.*", SearchOption.AllDirectories); IEnumerable<FileInfo> destinationList = destination.GetFiles("*.*", SearchOption.AllDirectories); areIdentical = sourceList.SequenceEqual(destinationList, myFileCompare); }); if (!areIdentical) { await DeleteFolders(dstDirs); await DeleteFiles(); await CopyNotExistedFiles(); await CopyModifiedFiles(); } }
static void Main(string[] args) { Console.WriteLine(FileCompare.CompareDirectories("PATH1", "PATH2", true)); Console.WriteLine(FileCompare.CompareFiles("FILENAME1", "FILENAME2")); }
private void StartComparing(object sender, EventArgs e) { FileCompare comparer = new FileCompare(File1Loc.Text, File2Loc.Text, OutputBox, ComparerProgressBar, this); comparer.StartComparing(); }
public string Save(string sourceDir, string targetDir, Semaphore MaxSizeSemaphore) { // Compare 2 directories System.IO.DirectoryInfo dir1 = new System.IO.DirectoryInfo(sourceDir); System.IO.DirectoryInfo dir2 = new System.IO.DirectoryInfo(fullSaveDir); IEnumerable <System.IO.FileInfo> list1 = dir1.GetFiles("*.*", System.IO.SearchOption.AllDirectories); IEnumerable <System.IO.FileInfo> list2 = dir2.GetFiles("*.*", System.IO.SearchOption.AllDirectories); // Create a list with the files to save FileCompare myFileCompare = new FileCompare(); var queryList1Only = (from file in list1 select file).Except(list2, myFileCompare); // Create the folder name string dateDay = DateTime.Now.ToString("dd"); string dateMonth = DateTime.Now.ToString("MM"); string dateYear = DateTime.Now.ToString("yyyy"); string dateHour = DateTime.Now.ToString("HH"); string dateMin = DateTime.Now.ToString("mm"); string dateSec = DateTime.Now.ToString("ss"); string folderName = "\\" + dateYear + "-" + dateMonth + "-" + dateDay + "_" + dateHour + "h" + dateMin + "min" + dateSec + "-FullSave"; string[] extensions = File.ReadAllLines("ExtensionFile.txt"); TimeSpan cryptingTime; cryptingTime = TimeSpan.Zero; StateFile statefile = new StateFile(); Save save = new Save(); FileSort fileSort = new FileSort(); queryList1Only = fileSort.PriorizeList(queryList1Only); // If there are files to save if (queryList1Only != null) { // Create the save directory Directory.CreateDirectory(targetDir + folderName); DateTime D1 = DateTime.Now; // Create all the needed directories foreach (string dirPath in Directory.GetDirectories(sourceDir, "*", System.IO.SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourceDir, targetDir + folderName)); } foreach (var file in queryList1Only) { Console.WriteLine(file.FullName); string fileName = file.Name; string vPath = file.FullName.Substring(sourceDir.Length + 1); bool FileLargerParameter = false; //Substring(sourceDir.Length + 1); if (File.Exists("FileSizeLimit.txt")) { if (FileSystem.GetFileInfo($"{sourceDir}/{vPath}").Length > Convert.ToInt64(File.ReadAllText($"{Environment.CurrentDirectory}/FileSizeLimit.txt"))) { MaxSizeSemaphore.WaitOne(); FileLargerParameter = true; } } try { bool file2Crypt = false; foreach (var ext in extensions) { if (ext == file.Extension) { file2Crypt = true; } } if (file2Crypt == true) { while (Controller.EnterpriseSoftwareRunning() == true) { } ; Process processus = new Process(); processus.StartInfo.FileName = Directory.GetCurrentDirectory() + "\\Cryptosoft.exe"; processus.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; Console.WriteLine("Transfert du fichier " + fileName + "..."); processus.StartInfo.Arguments = "-c " + sourceDir + "\\" + vPath + " fe3a2d57c378d7dc946589e9aa8cee011cae8013 " + targetDir + folderName + "\\" + vPath; processus.EnableRaisingEvents = true; processus.Exited += new EventHandler(myProcess_Exited); processus.Start(); Console.WriteLine("Cryptage du fichier" + fileName + " en cours..."); processus.WaitForExit(); cryptingTime += ((Process)processus).ExitTime - ((Process)processus).StartTime; } else { file.CopyTo(targetDir + "//" + folderName + "//" + vPath); } save.SaveUpdate(folderName, sourceDir, targetDir, fileName); statefile.UpdateStateFile(save); } // Catch exception if the file was already copied. catch (IOException copyError) { Console.WriteLine(copyError.Message); return("error"); } if (FileLargerParameter) { MaxSizeSemaphore.Release(); } } // Calculate the transfer time DateTime D2 = DateTime.Now; TimeSpan transferTime = D2 - D1; Console.WriteLine("Le temps de transfert total des fichiers a été de " + transferTime); Console.WriteLine("Le temps de cryptage total des fichiers a été de " + cryptingTime); // Create and update the logs file LogSave logSave = new LogSave(); logSave.CreateLog(folderName, sourceDir, targetDir, transferTime, cryptingTime); logSave.UpdateLogFile(logSave); } return(folderName); }
/// <summary> /// Entry point to start traversing and comparing files /// </summary> /// <param name="source">Source folder</param> /// <param name="destination">Destination folder</param> /// <param name="startDirScan">IProgress to indicate number of folders scanned so far and the name of the folder being currently inspected</param> /// <returns></returns> public async Task Compare(string source, string destination, IProgress<string> startDirScan) { await Task.Run(() => { AllDifferences = new ConcurrentBag<FileDiff>(); SourceRootFolder = source; DestinationRootFolder = destination; try { TraverseTreeParallelForEach( (sourceDirectory, destinationDirectory) => { try { startDirScan.Report(string.Format("Comparing {0} :: {1}", TotalDirectories, sourceDirectory.FullName)); var sourceFiles = sourceDirectory.EnumerateFiles(); var destinationFiles = destinationDirectory.EnumerateFiles(); FileSystemCompare compareByName = new FileSystemCompare(); FileCompare comparer = new FileCompare(); var onlyInSource = sourceFiles.Except(destinationFiles, compareByName); var onlyInDest = destinationFiles.Except(sourceFiles, compareByName); var inBothLists = sourceFiles.Intersect(destinationFiles, compareByName); foreach (var item in onlyInSource) { if (!isExclusion(item.FullName)) AllDifferences.Add(new FileDiff() { Source = item, Destination = null, DifferenceType = DiffType.ExistInSourceOnly, ItemType = ItemType.File }); } foreach (var item in onlyInDest) { if (!isExclusion(item.FullName)) AllDifferences.Add(new FileDiff() { Source = null, Destination = item, DifferenceType = DiffType.ExistInDestinationOnly, ItemType = ItemType.File }); } foreach (var item in inBothLists) { FileInfo destItem = destinationFiles.FirstOrDefault(x => x.Name == item.Name); if (!isExclusion(item.FullName) && !comparer.ExternalCompare(item as FileInfo, destItem)) { var itemFile = item as FileInfo; DiffType type = DiffType.None; if (!itemFile.LastWriteTimeUtc.ToString("yyyyMMMddHHmmss").Equals(destItem.LastWriteTimeUtc.ToString("yyyyMMMddHHmmss"))) type = DiffType.LastWritten; if (!itemFile.Length.Equals(destItem.Length)) type = DiffType.Lenght; AllDifferences.Add(new FileDiff() { Source = item, Destination = destItem, DifferenceType = type, ItemType = ItemType.File }); } } } catch (FileNotFoundException) { } catch (IOException) { } catch (UnauthorizedAccessException) { } catch (SecurityException) { } } ); } catch (ArgumentException) { Console.WriteLine(string.Format("The directory {0} does not exist", source)); } }); }
private void MoveHandler(object sender, RoutedEventArgs e) { if (db.Count() == 0) //TODO: Refactor so any and all GUI calls are handled elsewhere { MessageBox.Show("No files to move."); return; } MessageBoxResult result = MessageBox.Show("Are you sure you want to move the files?", "Move all files?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No); if (result == MessageBoxResult.No) { return; } bool OverwriteAll = false; bool NoToAll = false; for (int i = 0; i < db.Count(); i++) //we initially check for duplicate files or invalid directories { FilesToMove dir = db.GetDirInfo(i); List <string> removedFiles = new List <string>(); if (!Directory.Exists(db.GetDirInfo(i).GetDirectory())) { MessageBox.Show("Error: directory " + dir.GetDirectory() + " not found. Was this from an old save?", "Error", MessageBoxButton.OK, MessageBoxImage.Error); db.RemoveDirectory(i); continue; } foreach (string file in dir.GetFiles()) { if (!File.Exists(file)) { MessageBox.Show("Error: source file " + file + " not found. Was this from an old save?", "Error", MessageBoxButton.OK, MessageBoxImage.Error); removedFiles.Add(file); continue; } string destination = dir.GetDirectory() + "\\" + Path.GetFileName(file); if (File.Exists(destination) && !OverwriteAll) //file already exists at destination, and no overwrite flag set { FileCompare compare = new FileCompare(file, destination); compare.ShowDialog(); if (compare.RESULT == Result.YESTOALL) { OverwriteAll = true; } else if (compare.RESULT == Result.NO) { removedFiles.Add(file); } else if (compare.RESULT == Result.NOTOALL) { NoToAll = true; removedFiles.Add(file); } else if (compare.RESULT == Result.KEEPBOTH) { string ext = Path.GetExtension(file); string filename = Path.GetFileNameWithoutExtension(file); //First we need the amount of duplicates that are in the folder //Since we'll be off by one due to the original file not including a (x), we add one int offset = (Directory.GetFiles(dir.GetDirectory(), filename + " (?)" + ext)).Length + 2; destination = dir.GetDirectory() + "\\" + Path.GetFileNameWithoutExtension(file) + " (" + offset + ")" + ext; File.Move(file, Path.GetFullPath(file) + Path.GetFileName(destination)); //Renames file if (!dir.UpdateFileName(file, destination)) //Attempts to update the file name within the db { MessageBox.Show("Unexpected Error, something went wrong trying to keep both files. It may not exist.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } } else if (compare.RESULT == Result.CANCEL) { return; } } else if (File.Exists(destination) && NoToAll) { removedFiles.Add(file); } } } DisableButtons(); HidePreview(); imgPreview.Source = null; listViewDestination.ItemsSource = null; worker.RunWorkerAsync(); }
internal int CopyFiles(string p_source, string p_target) { var _result = 0; var _filesA = Directory.EnumerateFiles(p_source, "*.*", SearchOption.TopDirectoryOnly) .Where(f => ContainsFile(__config.SourceExcludeFiles, f) == false) .ToList(); var _filesB = Directory.EnumerateFiles(p_target, "*.*", SearchOption.TopDirectoryOnly) //.Where(f => ContainsFile(__config.TargetExcludeFiles, f) == false) .ToList(); var _file_compare = new FileCompare(__config.Offset); var _filesA_only = (from _file in _filesA select _file.ToLower()).Except(_filesB, _file_compare); foreach (var _f in _filesA_only) { if (__config.RemoveFiles == true) { try { var _fileName = Path.GetFileName(_f); var _destFile = Path.Combine(p_target, _fileName); File.Copy(_f, _destFile, true); Console.WriteLine("+'{0}': {1}", ++__config.CopiedFile, _f); } catch (Exception) { Console.WriteLine("+'{0}': {1}", ++__config.UnCopiedFile, _f); } } else { Console.WriteLine("+'{0}': {1}", ++__config.UnCopiedFile, _f); } _result++; } return _result; }
private void OnGUI() { if (_fileCompare == null) { _fileCompare = new FileCompare(); } DrawPathSelector("原始目录:", ref _fileCompare.Info.LeftComprePath); DrawPathSelector("对比目录:", ref _fileCompare.Info.RightComprePath); DrawPathSelector("补丁目录:", ref _fileCompare.Info.DiffPatchPath); EditorGUILayout.LabelField("当前存储配置版本:" + _fileCompare.Info.LastVersion); EditorGUILayout.BeginHorizontal(); GUI.enabled = !_isComparing && !_isInCreatePatch; if (GUILayout.Button("对比", GUILayout.Width(70))) { _compareCurProcess = 0; _isComparing = true; _compareStopWatch = Stopwatch.StartNew(); _compareStopWatch.Start(); if (_thread != null) { _thread.Abort(); } _thread = _fileCompare.Compare(OnCompareStep, OnCompareEnd, _fileCompare.Info.SortByDate); } //文件筛选设置 GUILayout.Space(10); //排除后缀 DrawExculdeSuffix(); EditorGUILayout.EndHorizontal(); //比较模式 DrawCompareMode(); //Bool比较设置项 DrawCompareToggleSetting(); //帮助提示 StringBuilder infoTipBuilder = new StringBuilder(); infoTipBuilder.AppendLine(LangHelp1); if (_fileCompare.Info.IsCompareFileDate) { infoTipBuilder.AppendLine(LangHelp2); } if (_fileCompare.Info.CompareMode == FileCompare.ECompareMode.Super_Ex) { infoTipBuilder.AppendLine(LangHelp3); } EditorGUILayout.HelpBox(infoTipBuilder.ToString(), MessageType.Info); //计数器 if (_compareStopWatch != null) { if (_compareStopWatch.IsRunning && _isComparing) { EditorGUILayout.LabelField(CalcStopWatchString()); } else { EditorGUILayout.LabelField(_compareStopWatchDisplayString); } } //若比较结果存在,则显示出来 _compareResultDis = _compareResult; if (_compareResultDis != null) { DrawPatchBtn(); EditorGUILayout.LabelField(string.Format(LangCompareSummaryTips, _compareMaxProcess, _compareResultDis.Count), _normalRichTextStyle); EditorGUILayout.BeginVertical(GUI.skin.box); _diffFileScrollPos = EditorGUILayout.BeginScrollView(_diffFileScrollPos); int thisPageIndex = _pageIndex * _pagePerCount; for (int i = thisPageIndex; i < _compareResultDis.Count && i < thisPageIndex + _pagePerCount; i++) { string path = _compareResultDis[i]; EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("O", GUILayout.Width(20))) { EditorUtility.OpenWithDefaultApp(Path.GetDirectoryName(_compareResultDis[i])); } bool useLeftFile = _fileCompare.Info.CreatePatchUseLeftFile.Contains(path); EditorGUI.BeginChangeCheck(); useLeftFile = EditorGUILayout.Toggle(useLeftFile, GUILayout.Width(10)); if (EditorGUI.EndChangeCheck()) { if (useLeftFile && !_fileCompare.Info.CreatePatchUseLeftFile.Contains(path)) { _fileCompare.Info.CreatePatchUseLeftFile.Add(path); } else { _fileCompare.Info.CreatePatchUseLeftFile.Remove(path); } Save(); } EditorGUILayout.LabelField(CalcDisplayPathStr(i + 1, path), _normalRichTextStyle); EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); DrawCreatePatchUseLeftFileSetting(); GUILayout.Space(20); } DrawPageSetting(); GUI.enabled = true; //检查是否显示/清理比较进度条 CheckDisplayProgress(); }
private void btnCompare_Click(object sender, EventArgs e) { try { txtLog.Text = ""; string SourcePath = labSource.Text; string TargetPath = labTarget.Text; DirectoryInfo dirSource = new DirectoryInfo(SourcePath); DirectoryInfo dirTarget = new DirectoryInfo(TargetPath); //取得目錄底下所有資料夾 DirectoryInfo[] SubDir = dirSource.GetDirectories("*", SearchOption.AllDirectories); //如果該目錄有子資料夾 if (SubDir.Count() > 0) { foreach (var Dir in SubDir) { txtLog.Text += "----------------開始偵測目標資料夾:" + Dir.FullName + "-----------------------" + Environment.NewLine; string TargetDir = Dir.FullName.Replace(SourcePath, TargetPath); if (!Directory.Exists(TargetDir)) { txtLog.Text += "目標資料夾不存在:" + TargetDir + Environment.NewLine; } IEnumerable <FileInfo> ListSource = Dir.GetFiles("*.*", SearchOption.TopDirectoryOnly); //取出所有Source檔案路徑 foreach (var F in ListSource) { //根目錄轉換 string OldPath = F.FullName; string NewFilePath = F.FullName.Replace(SourcePath, TargetPath); if (!File.Exists(NewFilePath)) { txtLog.Text += "目標檔案不存在:" + NewFilePath + Environment.NewLine; } else { try { //檔案若存在則進行檔案比對 FileCompare FC = new FileCompare(); FileInfo OldFile = new FileInfo(OldPath); FileInfo NewFile = new FileInfo(NewFilePath); if (OldFile != null && NewFile != null) { if (!FC.CheckInfo(OldFile, NewFile)) { txtLog.Text += "檔案不同步:" + NewFile.FullName + Environment.NewLine; } } } catch (Exception ex) { txtLog.Text += "錯誤:" + ex.InnerException + Environment.NewLine; } } } txtLog.Text += "----------------偵測目標資料夾結束:" + Dir.FullName + "-----------------------" + Environment.NewLine; } txtLog.Text += "比對完畢"; } else { //如果該資料夾內只有檔案 string[] SourcePaths = Directory.GetFiles(SourcePath); foreach (string ThisSourcePath in SourcePaths) { string thisTargetPath = ThisSourcePath.Replace(SourcePath, TargetPath); if (File.Exists(thisTargetPath)) { //檔案若存在則進行檔案比對 FileCompare FC = new FileCompare(); FileInfo OldFile = new FileInfo(ThisSourcePath); FileInfo NewFile = new FileInfo(thisTargetPath); if (OldFile != null && NewFile != null) { if (!FC.CheckInfo(OldFile, NewFile)) { txtLog.Text += "檔案不同步:" + NewFile.FullName + Environment.NewLine; } } } else { txtLog.Text += "目標檔案不存在:" + thisTargetPath + Environment.NewLine; } } txtLog.Text += "比對完畢"; } } catch (Exception ex) { txtLog.Text += ex.InnerException; } }