文件仅在复制/粘贴时锁定,而不是在剪切/粘贴时锁定

时间:2013-10-16 14:24:16

标签: c# file-io ioexception

我正在监视新文件的文件夹,当新文件存在时,我读取(并保存在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,告诉我该文件被另一个进程使用。 如果我剪切/粘贴文件夹,一切正常。 此外还会发生锁定问题如果我复制(但在这种情况下也会剪切)/将文件从另一台机器粘贴到受监视的文件夹中。

您对发生的事情有所了解吗?

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

谢谢!

1 个答案:

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

}