C # Reading and Writing text files are generally implemented using streamwriter (this is the case when reading a book, and this is basically the case after graduation). The Code is usually as follows:
Using (streamwriter Sw = new streamwriter (logpath, true, encoding. utf8 ))
{
Sw. writeline (MSG );
}
If it is web development or other multithreading, the lock is usually used (use lock). If it is different from the lock, there will be an error such:
On this day, a colleague recommended that I use filestream instead of lock. The Code is as follows:
Using (filestream FS = new filestream (logpath, filemode. append, fileaccess. Write, fileshare. readwrite ))
{
Using (streamwriter Sw = new streamwriter (FS ))
{
Sw. Write (MSG );
}
}
After testing, I found that there is no problem with multithreading, so I checked the definition of streamwriter below,
[SecurityCritical]internal StreamWriter(string path, bool append, Encoding encoding, int bufferSize, bool checkHost) : base(null){ if (path == null) { throw new ArgumentNullException("path"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } if (path.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Stream streamArg = CreateFile(path, append, checkHost); this.Init(streamArg, encoding, bufferSize, false);}[SecurityCritical]private static Stream CreateFile(string path, bool append, bool checkHost){ return new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);}
Note that the createfile method here uses fileshare. Read. The differences between read and readwrite are as follows:
Read allows subsequent open file reading. If this flag is not specified, before the file is closed, any requests that open the file for reading (requests sent by this process or another process) will fail. However, even if this flag is specified, you may still need additional permissions to access the file.
Readwrite allows subsequent open files to be read or written. If this flag is not specified, any requests (sent by this process or another process) that open the file for reading or writing will fail before the file is closed. However, even if this flag is specified, you may still need to attach permissions to access the file.
I want to know all about the fileshare attribute, but do you know about streamwriter and filestream here. The usage of streamreader, streamwriter, and filestream is described as follows:
Http://blog.csdn.net/sansan52048/article/details/9160995
Therefore, we recommend that you use the underlying filestream whenever possible when file operations are involved. In this way, software must be continuously learned, summarized, and advanced.