读取可能正在更新的文件

时间:2015-03-31 01:32:30

标签: c# locking ioexception

在阅读之前是否还等待此文件打开?正在读取的文件将写入相当多,并且不希望此错误继续发生。在尝试阅读之前,我应该延迟一段时间吗?这是一个实时统计页面,因此重新加载该页面将会发生很多。

System.IO.IOException: The process cannot access the file because it is being used by another process.

1 个答案:

答案 0 :(得分:1)

要测试文件是否已锁定,您可以使用此功能:

    protected virtual bool IsFileLocked(string filePath)
    {
        FileInfo file = new FileInfo(filePath);
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

通常在正常逻辑中使用异常并不好,但在这种情况下,您可能没有选择权。您可以每隔X秒调用一次,以检查锁定。替代方案可以是使用文件系统观察器对象来监视文件。如果不了解您的具体用例,很难说。