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

本文关键字:锁定 文件 复制 | 更新日期: 2023-09-27 18:35:33

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

你对正在发生的事情有所了解吗?

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

谢谢!

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

这是我做的一个小片段,以确保文件完成复制或未被另一个进程使用。

 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
}