Can I prevent a StreamReader from locking a text file whilst it is in use?

后端 未结 2 1150
灰色年华
灰色年华 2020-12-09 10:01

The StreamReader locks a text file whilst it is reading it.
Can I force the StreamReader to work in a \"read-only\" or \"non locking\" mode?

My workaround would

相关标签:
2条回答
  • 2020-12-09 10:12

    Thought I'd add some context, StreamReader does not lock a file for reading only for writing whist it is being read. Take a look at the code below from the StreamReader class.

     new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, FileOptions.SequentialScan);
    

    Notice the default FileAccess.Read parameter taken for MSDN http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

    Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

    Again taken from MSDN to allow reading and writing use FileAccess.ReadWrite instead (as suggested by Jb Evain).

    Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

    0 讨论(0)
  • 2020-12-09 10:14

    You can pass a FileStream to the StreamReader, and create the FileStream with the proper FileShare value. For instance:

    using (var file = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var reader = new StreamReader (file, Encoding.Unicode)) {
    }
    
    0 讨论(0)
提交回复
热议问题