Home > Backend Development > C++ > Can File Locking Be Checked in C# Without Using Exceptions?

Can File Locking Be Checked in C# Without Using Exceptions?

Barbara Streisand
Release: 2025-02-02 22:11:09
Original
917 people have browsed it

Can File Locking Be Checked in C# Without Using Exceptions?

Deterministic File Locking Check in C#

C# developers often encounter the "File in use by another process" error when attempting to access a file before it's been saved. While exception handling is standard practice, a more predictable approach is desirable for certain applications.

This can be achieved using FileInfo.Open with FileAccess.Read and FileShare.None. A successful file opening (without exceptions) indicates the file is available. Conversely, an IOException signifies a lock.

Here's an improved method:

protected virtual bool IsFileLocked(FileInfo file)
{
    // Attempt to open the file for reading with exclusive access
    try
    {
        using (FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            // Successful opening; file is not locked
            return false;
        }
    }
    catch (IOException)
    {
        // File is locked
        return true;
    }
}
Copy after login

This method offers a deterministic approach to file lock detection, avoiding reliance on exceptions. However, it's crucial to remember this only works reliably for files not opened with write access. Attempting to use FileAccess.ReadWrite with FileShare.None will always fail, even if the file is unlocked.

The above is the detailed content of Can File Locking Be Checked in C# Without Using Exceptions?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template