C# StreamReader, StreamWriter default internal FileStream

By admin - Last updated: Monday, April 6, 2009 - Save & Share - Leave a Comment

I was wondering about the default FileStream object configuration within StreamWriter constructor, specifically the FileShare parameter of the FileStream. I’d like to find out if other processes are able to read the content at the same time while StreamWriter writes the content into the file.

using (StreamWriter writer= new StreamWriter(“test.txt”))
     while(true); // note, it fills the disk up very quickly.
         writer.WriteLine(“test StreamWriter”);

In order to allow this behavior, I need to find out the value of FileShare parameter of the FileStream created internally within StreamWriter.

After digging around with the disassembler, I ended up with the following code within StreamWriter,

private static Stream CreateFile(string path, bool append)
    return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, 0×1000, FileOptions.SequentialScan);

OK, the internal FileStream was created by CreateFileMethod, and the FileShare.Read allows others read the file simutaneously without affecting its writing process. You also see the default buffer size is 0×1000 = 4096 bytes.

Out of curiosity, what is the internal FileStream of StreamReader? one line of code says

Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 0×1000, FileOptions.SequentialScan);

Again, it allows other processes read share as well and the default buffer is 4096 bytes too.

Posted in Code Notes • Tags: Top Of Page

Write a comment

Captcha: 7 + five =