关于此解决方案的更新的注释 :
FileAccess.ReadWrite只读文件的“ 检查”
将失败,因此该解决方案已被修改为“”进行检查
FileAccess.Read。尽管此解决方案有效,因为
FileAccess.Read如果文件上具有写入或读取锁定,尝试进行检查将失败,但是,如果文件上没有写入或读取锁定(即已打开),则此解决方案将不起作用(用于读取或写入)具有FileShare.Read或FileShare.Write访问权限。
原文: 我在过去的几年中一直使用此代码,但至今没有任何问题。
了解您对使用异常的犹豫,但是您无法始终避免使用它们:
protected virtual bool IsFileLocked(FileInfo file){ try { using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None)) { stream.Close(); } } 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; } //file is not locked return false;}


