在尝试读取文件之前,有没有任何方法可以先测试文件是否正在使用中?例如,如果文件仍在被写入或被认为正在使用,则此代码块将抛出异常:
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语句,但这种方法感觉非常不专业。我本来期望在System.IO.FileInfo
中会有更好的解决方案,但实际上并没有。
你们有更好的想法吗?