mostlylucid

scott galloway's personal blog...
posts - 911, comments - 723, trackbacks - 11

My Links

News

Archives

Post Categories

Misc. Coding

.NET and Locked Files...

OK, can anyone explain why I can't check explicitly if I can lock a file before reading from it (i.e., check that no-one else is locking the file before trying to read from it). I'm using the marvellous FileSystemWatcher to wait for files being created in a directory before triggering a job - fine but there doesn't seem to be any easy way to check is a file is 'readable' before starting to read... Right now my way of doing this task is to attempt to read - and place a Read lock - on the file using the FileStream  and catch the error it throws when the file is locked by another process...like so...but this really doesn't feel right. I balk at the idea of using exceptions (which are also REALLY slow) for this kind of task...why doesn't FileStream.CanRead check for locks BEFORE opening the file???

        private static int m_ReadAttempts = 0;
        private string  ReadFileFromDisk(string filePath)
        {
            try
            {
                if(!File.Exists(filePath))
                {
                    MessageBox.Show("Sorry, but the file specified " + Environment.NewLine + filePath + Environment.NewLine + "Cannot be found");
                    return string.Empty;
                }
            using(FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read,FileShare.Read))
                {
                        using(StreamReader sr = new StreamReader(fs)) 
                        {
                            string tmpStr = sr.ReadToEnd();
                            sr.Close();
                            m_ReadAttempts =0;
                            return tmpStr;
                        }
                
                }        
            }
            catch(IOException ex)
            {
                    if(m_ReadAttempts < 10)
                {
                    Thread.Sleep(500);
                    m_ReadAttempts++;
                    return ReadFileFromDisk(filePath);
                }
                else
                {
                    throw ex;
                }
            }
        }

Print | posted on Monday, November 17, 2003 9:54 PM | Filed Under [ .NET Help! ]

Feedback

Gravatar

# re: .NET and Locked Files...

Simple: the operation wouldn't be atomic. For example, say your function call "IsFileLocked" existed. Process A calls IsFileLocked, which returns false. Right afterwards, Process B opens the file for read. Process A tries to open the file, which fails. Therefore process A will still need to try/catch exceptions.

Therefore there's virtually no point in supporting this functionality.

Christian Laforte
Dakis - Director of 3D Technology
12/11/2003 3:33 PM | Christian Laforte
Gravatar

# re: .NET and Locked Files...

Accepted, but you could prevent this eventuality by having another parameter - called for example, LockFile - so, IsFileLocked(string filePath, bool lockFile) would check it was locked then lock the file - preventing access from another process. Obviously some way would be required to account for the time between the check and the lock (don't know if that is a atomic transaction from the filesystem)...but is might work :-) You could even have a third parameter which could act as some form of 'lock timeout' preventing enternal locks on files...
12/11/2003 5:03 PM | Scott Galloway
Gravatar

# re: .NET and Locked Files...

Nice post - this was exactly what I needed to build and your code saved me the 30 minutes that you took!
Thanks.
12/16/2003 8:12 PM | Benjamin Mitchell
Gravatar

# re: .NET and Locked Files...

I disagree with Christian. Having such a function is not virtually pointless. A return value of false may not guarantee that the file is readable in the next statement, but a return value of true saves you the trouble of trying to open it and the overhead of the exception.

You could then write a loop while (IsFileLocked) and wait. When it finally returns false, you can attempt to read it. If it then happens to be locked again, that's what the exception handler is for. Now you've reduced the occurrence of exceptions dramatically, because instead of them firing whenever a file is locked (occasionally), they only fire if a file happened to unlock and immediately lock again, while the logic in this program checked in between the two steps (very rare).
6/18/2009 7:35 PM | Steven Nicolaou
Comments have been closed on this topic.

Powered by: