在尝试打开文件进行读取之前,有什么方法可以先测试文件是否正在使用中?例如,如果文件仍在被写入或被认为正在使用,则此代码块将引发异常:
try
{
FileStream stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (IOException ex)
{
// ex.Message == "The process cannot access the file 'XYZ' because it is being used by another process."
}
我环顾四周,我能找到的最好的方法是执行某种轮询,里面有一个 try catch,感觉很hacky。我希望会有一些东西,System.IO.FileInfo
但没有。
有什么更好的方法吗?