【问题标题】:File locked only if copy/paste, not if cut/paste仅在复制/粘贴时锁定文件,而不是在剪切/粘贴时锁定
【发布时间】:2013-10-16 14:24:15
【问题描述】:

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

你知道发生了什么吗?

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

谢谢!

【问题讨论】:

  • 你如何监控文件夹..向我们展示代码..你在使用 FileSystemWatcher 吗?
  • 我正在使用 FileSystemWatcher(在一个包装类中以监控多个文件夹)
  • 很可能与您的FileSystemWatcher 有冲突!给我们看代码
  • 当然!我使用了这个代码:codeproject.com/Articles/271669/…
  • 我会说从另一台机器上它只是更多,因为文件完成它需要时间并且复制过程持有文件人质。使用文件添加逻辑以确保在执行任何处理之前完全可以访问文件时,这是一种很好的做法。 FileSystem 对文件的访问速度非常快,因此您的流程逻辑会立即启动,因此您要确保它没有被锁定。

标签: c# file-io ioexception


【解决方案1】:

这是我做的一个小 sn-p 操作,以确保文件已完成复制或未被另一个进程使用。

 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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多