Mike Flynn
Mike Flynn

Reputation: 24325

Reading file that might be updating

Is there anyway to wait for this file to open before reading it? The file that is being read will be writing to quite a bit and dont want this error to keep happening. Should I do a while loop with a delay before trying to read it? This is a live stats page so reloading of that page will happen quite a bit.

System.IO.IOException: The process cannot access the file because it is being used by another process.

Upvotes: 0

Views: 101

Answers (1)

Tyler Day
Tyler Day

Reputation: 1718

To test if the file is locked, you can use this function:

    protected virtual bool IsFileLocked(string filePath)
    {
        FileInfo file = new FileInfo(filePath);
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

Usually it is not good to use exceptions in your normal logic, but in this case you may not have a choice. You could call this every X seconds possibly, to check for locks. An alternative may be to use a file system watcher object to monitor a file. It's hard to say without knowing more about your specific use case.

Upvotes: 1

Related Questions