繁体   English   中英

有没有办法在FileSystemWatcher.Changed事件中尝试读取之前检查文件的可读性?

[英]Is there any way to check file readability before trying to read it in FileSystemWatcher.Changed event?

我使用FileSystemWatcher来监视某些文件夹的更改。 当它触发文件更改事件时,我需要读取该文件并更新一些内容。 问题是,当触发此事件时,即使以这种方式仍然禁止目标文件读取FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

是否还有其他事件通知文件已结束更改? 或者无论如何要创建一些等待文件读取能力的服务员通过一些标准方式(WinAPI等)。 或者循环尝试catch是唯一的选择?

如果文件流可用,则应使用以下帮助程序方法返回文件流。

public static FileStream WaitForFile(string fullName)
{
    FileStream fs = null;
    int numTries = 0;
    while (true)
    {
        ++numTries;
        try
        {
            //try to open the file
            fs = new FileStream(fullName, FileMode.Open, FileAccess.Read, FileShare.None, 100);

            fs.ReadByte();//if it's open, you can read it
            fs.Seek(0, SeekOrigin.Begin);//Since you read one byte, you should move the cursor position to the begining.                    
            break;
        }
        catch (Exception ex)
        {
            if (numTries > 10)//try 10 times
            {
                return fs;//Or you can throw exception
            }
            System.Threading.Thread.Sleep(10000);//wait 
        }
    }
    return fs;
}

不幸的是,无法保证在Changed事件引发时您可以访问该文件。 是一个让您感兴趣的主题 ,如何等待文件可用于Open。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM