In programming, access to the currently used by another process may cause errors. This may happen when the program tries to access the file that has not been saved back to the file system. To avoid such errors, a reliable method is needed to determine whether the file is currently in use.
Although abnormal treatment is a common method, some developers are more inclined to avoid it due to specific preferences or coding styles. Fortunately, there are other methods to check the availability of files.
A effective way to verify the lock state of the file is to use the FileStream class in C#. The following code demonstrates a technology using Fileshare.none and FileAccess.read:
By using , the file will be opened by the land to read. If any other process is accessing the file,
will be thrown, indicating that the file is currently locked. This method allows reliably check the availability of files without using abnormal treatment. If the file does not exist or cannot be accessed, the constructor of theprotected virtual bool IsFileLocked(FileInfo file) { // 尝试以独占读取访问方式打开文件。 using (FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.None)) { // 如果文件未锁定,此行将成功执行。 stream.Close(); } // 文件未锁定。 return false; }
The above is the detailed content of How Can I Check File Availability in C# Without Using Exception Handling?. For more information, please follow other related articles on the PHP Chinese website!