文件正在被复制吗?

时间:2012-09-25 18:03:24

标签: c# .net file-io

  

可能重复:
  C# - from time to time check if a file exists and read from it

我正在使用文件监视器来检查文件是否在目录中被写入。如果是,那么我想打开它并移到另一个目录。

我的方法也是使用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(),直到它被完全复制并且没有进程正在使用它。

我如何联系到它?

2 个答案:

答案 0 :(得分: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) {}
}

答案 1 :(得分: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);
            }     
        }       
    }