Back to ".NET and Locked Files..."

This is a viewer only at the moment see the article on how this works.

To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk

This is a preview from the server running through my markdig pipeline

.NET C# Imported mostlylucidcouk

.NET and Locked Files...

Friday, 20 February 2004

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;
                }
            }
        }
logo

© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.