FileSystemWatcher - is File ready to use

后端 未结 6 1099
[愿得一人]
[愿得一人] 2020-12-03 17:45

When a file is being copied to the file watcher folder, how can I identify whether the file is completely copied and ready to use? Because I am getting multiple events duri

6条回答
  •  感动是毒
    2020-12-03 18:38

    Here is a method that will retry file access up to X number of times, with a Sleep between tries. If it never gets access, the application moves on:

    private static bool GetIdleFile(string path)
    {
        var fileIdle = false;
        const int MaximumAttemptsAllowed = 30;
        var attemptsMade = 0;
    
        while (!fileIdle && attemptsMade <= MaximumAttemptsAllowed)
        {
            try
            {
                using (File.Open(path, FileMode.Open, FileAccess.ReadWrite))
                {
                    fileIdle = true;
                }
            }
            catch
            {
                attemptsMade++;
                Thread.Sleep(100);
            }
        }
    
        return fileIdle;
    }
    

    It can be used like this:

    private void WatcherOnCreated(object sender, FileSystemEventArgs e)
    {
        if (GetIdleFile(e.FullPath))
        {
            // Do something like...
            foreach (var line in File.ReadAllLines(e.FullPath))
            {
                // Do more...
            }
        }
    }
    

提交回复
热议问题