FileStream locking a file for reading and writing

19,712

Solution 1

The FileShare.None flag does not cause threads to queue, it just locks the file, hence the exception that you get. To provide mutually exclusive access you can lock a shared object prior to writing.

But you say this "Now my program is a multithreaded application. Any thread could be trying to write to this file." Now, do these threads all use exactly the same method to write to the file? Let's assume they do, then this should work ...

Create a static class variable ...

private static object lockObject = new object();

Use it here ...

lock (lockObject) 
{
    using(var sw = new StreamWriter(fs))
    {
       sw.Write(str + text);
    }
}

I have made some assumptions about the threads, so you may have to look up info on synchronization if this doesn't work or provide some more info to us.

Also, please close your StreamReader earlier (in case the method returns earlier). Close it immediately after you use it or better yet use using.

Solution 2

Try Thread Synchronization. You can find more details from this link.

Solution 3

As in the MSDN reference the Close method

Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.

Thus it seems that the subsequent call to StreamWriter fails to use a closed resource, giving you the message "the file is not writable".

Try this

            using (var fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            using (var sr = new StreamReader(fs))
            {
                var str = sr.ReadToEnd();
                // ...

                using (var sw = new StreamWriter(fs))
                {
                    // ...
                }
            }
        }
Share:
19,712
Talon
Author by

Talon

Stackoverflow has saved me countless hours! It's the place I go to check if I am doing it the best way. It's the place I go when I'm feeling lazy and don't want to figure out even the simplest pieces of code. It's the place I go when I have a Eureka moment and want to share my solution that I am proud of. It's the place I go when I when nothing seems to work and I just need some direction. Stackoverflow is a critical part of my life as a developer! I'm not the best developer but now and then I have moments of brilliance, I like to share it and it is a very rewarding experience to get that vote up and know that you have helped someone just like you. I am #SOreadytohelp others who need it.

Updated on June 05, 2022

Comments

  • Talon
    Talon almost 2 years

    I have the following code block which is giving me a headache.

    Logically it should work as I am using the filestream providing the lock within the using statement. When it gets to the line that creates the StreamWriter, it fails saying "the file is not writable".

    Now my program is a multithreaded application. Any thread could be trying to write to this file. I need the program to lock the file, read the contents, check the contents, then write back any changes. During that process, no other thread should be able to access that file.

    using (var fs = File.Open(fileLoc, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
    {
        var sr = new StreamReader(fs);
        var str = sr.ReadToEnd();
        var strArray = str.Split(',');
        if (strArray.Any(st => st == text))
        {
            return;
        }
        sr.Close();
    
        var sw = new StreamWriter(fs);
        sw.Write(str + text);
        sw.Flush();
        sw.Close();
    }