Knowing if a file is locked or not

Asked

Viewed 284 times

4

How do I know if a file is blocked or not? I have perfected this code and I would like to know from you whether it is correct or for the better. Another question is if it is corrupted, the check below is valid?

public bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
    return false;
}
  • This might help: http://stackoverflow.com/questions/1304/how-to-check-for-file-lock later I try to write a reply. BTW +1.

1 answer

1


Apparently this is the most suitable way to do this check. By the way, is identical to this reply here from Soen.

In the same answer, there is still the possibility to verify whether the exception is a sharing Violation (violation of sharing) or a lock Violation (violation of writing lock):

FileStream stream = null;

try
{
    stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException ex)
{
   if (IsFileLocked(ex))
   {
       // Faça alguma coisa
   } 
}
finally
{
if (stream != null)
    stream.Close();
}

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
    int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
    return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}
  • Got it, it improved the code more. It’s good now. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.