I have the following script, I have to copy several (about 10,50,200, ...) files. I do it synchronously one by one. This is my piece of code for this.
static void Main(string[] args) { string path = @""; FileSystemWatcher listener = new FileSystemWatcher(path); listener.Created += new FileSystemEventHandler(listener_Created); listener.EnableRaisingEvents = true; while (Console.ReadLine() != "exit") ; } public static void listener_Created(object sender, FileSystemEventArgs e) { while (!IsFileReady(e.FullPath)) ; File.Copy(e.FullPath, @"D:\levani\FolderListenerTest\CopiedFilesFolder\" + e.Name); }
So, when files are created in a folder and they are ready to use, I copy this file one by one, but I need to start copying as soon as any file is ready for use. Therefore, I think I should use Threads. So. How to implement parallel copying?
@Chris
Check if the file is ready
public static bool IsFileReady(String sFilename) { // If the file can be opened for exclusive access it means that the file // is no longer locked by another process. try { using (FileStream inputStream = File.Open(sFilename, FileMode.Open, FileAccess.Read, FileShare.None)) { if (inputStream.Length > 0) { return true; } else { return false; } } } catch (Exception) { return false; } }
source share