2013-10-16 204 views
1

我监视新文件的文件夹,并在新的文件存在我读(和一个txt保存)文件如下未锁定:文件只有当复制/粘贴,如果剪切/粘贴

FileStream file = File.Open(this.filePath, FileMode.Open, FileAccess.Read); 
StreamReader reader = new System.IO.StreamReader(file); 
string text = reader.ReadToEnd(); 
reader.Close(); 

如果我复制/粘贴文件夹中的源文件,我收到一个IOExcpetion,告诉我该文件被另一个进程使用。 如果我在文件夹中剪切/粘贴,所有的作品。 此外锁定问题也会发生如果我复制(但也切入这种情况下)/从另一台机器粘贴文件到受监视的文件夹中。

你知道发生了什么吗?

有一种更安全的方式来访问文件,以避免这种类型的锁?

谢谢!

+0

你是如何监控folder..Show我们code..Are您使用FileSystemWatcher的前实现这一点? – Anirudha

+0

我正在使用FileSystemWatcher(在一个包装类中为了监视多个文件夹) – ff8mania

+0

很可能与您的'FileSystemWatcher'有冲突!向我们展示代码 – Anirudha

回答

0

这是我确保文件完成复制或不被另一个进程使用的一小段代码。

private bool FileUploadCompleted(string filename) 
    { 
     try 
     { 
      using (FileStream inputStream = File.Open(filename, FileMode.Open, 
       FileAccess.Read, 
       FileShare.None)) 
      { 
       return true; 
      } 
     } 
     catch (IOException) 
     { 
      return false; 
     } 
    } 

然后您可以将流程逻辑

while (!FileUploadCompleted(filePath)) 
{ 
    //if the file is in use it will enter here 
    //So you could sleep the thread here for a second or something to allow it some time 
    // Also you could add a retry count and if it goes past the allotted retries you 
    // can break the loop and send an email or log the file for manual processing or 
    // something like that 

}