Search code examples
c#filefilesystemwatcher

File.Move() closes Console window automatically in C#


I have a simple C# Console application in which I use FileSystemWatcher and Moving files from one destiantion to another when they are created. My code looks like this:

    public static void WatchForFiles()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        //folder path is path to folder
        watcher.Path = folderPath;

        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
            | NotifyFilters.FileName | NotifyFilters.DirectoryName;

        //Add event handlers           
        watcher.Created += new FileSystemEventHandler(File_OnChanged);        

        //Begin watching
        watcher.EnableRaisingEvents = true;
    }


    public static void File_OnChanged(object sender, FileSystemEventArgs e)
    {
        //destiantion path is path to folder
        string destiantionFileFullPath = destianationPath + e.Name;
        if (!File.Exists(destiantionFileFullPath))
        {
            File.Move(e.FullPath, destiantionFileFullPath);
        }
    }

When I copy a file first time it is moved normally. But after that or if I copy two or more files my console windows is closed automatically. I think I should use IAsyncResult but I don't know how. I tried Tasks but that didn't help. Firs copying file and then deleting didn't help either. What causes to this and how can I prevent this? Thanks in advance


Solution

  • From experience, the use of FileWatcher to monitor files as they are dumped and (possibly) move them is more trouble than one would want to manage. Simple reason being that if files are dumped into the directory when your application is down, the FileWatcher wont catch them. I prefer using a Timer that polls at intervals, checking if there are files in the directory and moving them. Using this approach, if new files are dumped in the folder when the application is down (say for maintenance), they will be moved as soon as the app is restarted and the timer starts polling