FileStream locking a file for reading and writing

前端 未结 3 1584
一生所求
一生所求 2021-01-12 04:30

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.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-12 05:08

    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))
                    {
                        // ...
                    }
                }
            }
    

提交回复
热议问题