0

可能重复:
C# - 不时检查文件是否存在并从中读取

我正在使用文件观察器来检查文件是否在目录中创建。如果是,那么我想打开它并删除到另一个目录。

我的方法也是用来FileShare.None确保独占访问。我所做的是:

class Program
    {
        private static void Main(string[] args)
        {
            FileSystemWatcher fileWatcher = new FileSystemWatcher();
            fileWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            fileWatcher.Created += fileWatcher_Created;
            fileWatcher.EnableRaisingEvents = true;
            Console.ReadLine();
        }

        private static void fileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            WorkOnFile(e.FullPath);   
        }


        //must be done completely. How do I ensure it?
        private static void WorkOnFile(string fileName)
        {
            using (FileStream f = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
            {
                Thread.Sleep(40000); // some long operations
            }            
        }
  }

底线是,WorkOnFile()对于一个文件,必须完全且只执行一次。如果一个文件被复制,那么我需要WorkOnFile()再次调用,直到它被完全复制并且没有进程正在使用它。

我如何达到它?

4

2 回答 2

1

如果您需要尽快移动该文件,您可以尝试使用 FileWatcher 监控“LastWrite”,并在稍有延迟后尝试移动该文件。

我必须做一些非常相似的事情,但并不着急,重要的是文件被可靠地移动。所以我改为使用 System.Timers.Timer 每分钟运行一次:

var scanDirectoryIn = new DirectoryInfo(folderIn);
foreach (var fileInfo in scanDirectoryIn.GetFiles())
{
  if (fileInfo.Extension != ".csv") continue;
  if (DateTime.UtcNow.Subtract(fileInfo.LastWriteTimeUtc).TotalMinutes < 5) continue;
  try
  {
    fileInfo.MoveTo(folderOut + "\\" + fileInfo.Name);
  }
  catch (Exception) {}
}
于 2012-09-25T18:54:10.790 回答
0
//must be done completely. How do I ensure it?
    private static void WorkOnFile(string fileName)
    {
        while(true){
            try{
                using (FileStream f = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    Thread.Sleep(40000); // some long operations

                    break; //exit while() infinite loop
                }
            }
            catch(Exception e){
                //file is locked because being written. wait a few seconds then retry
                Thread.Sleep(10000);
            }     
        }       
    }
于 2012-09-25T18:35:18.013 回答