Know if a file is locked or not

4

How do I know if a file is locked or not? I have improved this code and would like to know if you are correct or better. Another question is if it is corrupted, is the verification below 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;
}
    
asked by anonymous 05.11.2014 / 18:45

1 answer

1

Apparently this is the most appropriate way to do this check. By the way, is identical to this answer here from SOen .

In the same response, there is still the possibility of checking whether the exception is a violation violation (violation of sharing) or a lock violation :

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;
}
    
05.11.2014 / 18:48