C#讀寫文本文件一般都是用StreamWriter來實現(讀書的時候就這樣用,畢業后這幾年基本也是這樣干的),通常代碼如下:
using (StreamWriter sw = new StreamWriter(logpath,true,Encoding.UTF8)) { sw.WriteLine(msg); }
如果是web開發或則其他多線程的時候一般都是加鎖(用lock),如果不同lock就會有error如:

這天我一同事推薦我說用FileStream可以不用lock,在多線程的情況下是不會有問題的,代碼如下:
using (FileStream fs = new FileStream(logpath, FileMode.Append, Fileaccess.Write, FileShare.ReadWrite)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(msg); } }
經過測試后發現在多線程下卻實沒有問題,于是回頭查看了以下StreamWriter的定義,
[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);}注意這里的CreateFile方法,里面用的是FileShare.Read,有關Read和ReadWrite 的區別如下:
Read 允許隨后打開文件讀取。如果未指定此標志,則文件關閉前,任何打開該文件以進行讀取的請求(由此進程或另一進程發出的請求)都將失敗。但 是,即使指定了此標志,仍可能需要附加權限才能夠訪問該文件。
ReadWrite允許隨后打開文件讀取或寫入。如果未指定此標志,則文件關閉前,任何打開該文件以進行讀取或寫入的請求(由此進程或另一進程發出)都將失敗。但是,即使指定了此標志,仍可能需要附加權限才能夠訪問該文件。
我想單獨就FileShare屬性大家都知道,可是在這里就StreamWriter和FileStream大家是否也知道這個問題了。有關StreamReader/StreamWriter與FileStream用法詳解如下:
http://blog.csdn.net/sansan52048/article/details/9160995
所以在涉及到文件操作的時候建議大家盡量用底層的FileStream操作。軟件就是這樣要不斷學習、不斷總結、不斷前進。
新聞熱點
疑難解答