Q: Is there a way to check if a file is in use?

D: I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error: "File in use by another process".

I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it?

Test Case #13


File ID: #937558-0-cc


internal static bool IsFileLocked(FileInfo file)
{
    FileStream fileStream = null;
    try
    {
        fileStream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        return true;
    }
    finally
    {
        if (fileStream ! = null)
            fileStream.Close();
    }
    return false;
}

  1. -1. This is a poor answer, because the file could become locked by another thread/process after it is closed in IsFileLocked, and before your thread gets a chance to open it.
  2. You might be wondering what is going on. Do not be alarmed. you are just being subject to the wrath of the Daily WTF community: http://thedailywtf.com/Comments/The-Right-Way-to-Find-a-File.aspx#402913
  3. This is a great solution, but I have one comment - you may wan't to open the File with access mode FileAccess.Read since ReadWrite will always fail if the file happens to be read-only.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: