I want to clarify the algorithm of work before writing a program.

There are two folders. If the second is not, then create. In the first folder are the files. If there are no files in the second one, copy the contents of the first one into it. Further, in real time, see the time for changing the files of the first folder. If in the first folder the contents are “fresher” than in the second, copy from the first to the second.

There is a code for txt files (see code below). How can I unload the entire directory from 1 folder and compare how I compared in the code. If there are tips, can you add the code? Any help will come down, I will be very grateful.

FileInfo q = new FileInfo(@"1\1.txt"); FileInfo w = new FileInfo(@"2\2.txt"); DateTimeOffset a = q.LastWriteTime; DateTimeOffset b = w.LastWriteTime; if (a < b) { w.Delete(); q.CopyTo(@"2\2.txt"); } if (q.Exists == false) { q.Delete(); w.CopyTo(@"1\1.txt"); } 

1 answer 1

I wrote in a hurry, I hope you will be able to refactor the code.

 Dictionary<string, DateTimeOffset> dict_files_1 = new Dictionary<string, DateTimeOffset>(); string[] array_files_1 = Directory.GetFiles(@"D:\TEST\1"); foreach(string path in array_files_1) { FileInfo f_info = new FileInfo(path); string[] array = path.Split('\\'); string filename = array[array.Length - 1]; dict_files_1.Add(filename, f_info.LastWriteTime); } if(!File.Exists(@"D:\TEST\2")) { Directory.CreateDirectory(@"D:\TEST\2"); } string[] array_files_2 = Directory.GetFiles(@"D:\TEST\2"); if(array_files_2.Length == 0) { foreach(string path in array_files_1) { string[] array = path.Split('\\'); string filename = array[array.Length - 1]; File.Copy(path, @"D:\TEST\2\" + filename); } } else { foreach(string path in array_files_2) { FileInfo f_info = new FileInfo(path); string[] array = path.Split('\\'); string filename = array[array.Length - 1]; if(!dict_files_1.ContainsKey(filename)) { f_info.CopyTo(@"D:\TEST\2\" + filename); } else { DateTimeOffset dt = dict_files_1[filename]; if(dt > f_info.LastWriteTime) { File.Delete(@"D:\TEST\2\" + filename); f_info.CopyTo(@"D:\TEST\2\" + filename); } } } }