讀取txt檔案時,提示例外:
檔案“..\Log\all_info.txt”正由另一行程使用,因此該行程無法訪問此檔案
原因:
日志檔案通過lognet生成的日志檔案(C#使用log4net記錄日志),自動任務一直在進行,檔案流沒有關閉,
所以獲取檔案內容時,會提示行程被占用,
嘗試方案:
通過System.IO.File讀取 -- ReadAllLines/ReadAllText等方法,報錯行程占用例外
var fileContent = File.ReadAllText(_filename);
通過FileStream讀取資料
1 using (FileStream fsRead = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 2 { 3 int fsLen = (int)fsRead.Length; 4 byte[] heByte = new byte[fsLen]; 5 fsRead.Read(heByte, 0, heByte.Length); 6 string myStr = System.Text.Encoding.UTF8.GetString(heByte); 7 }
測驗:OK
重點在FileShare這個引數,FileShare.ReadWrite 允許打開檔案后,依然可以進行讀取,

也使用StringBuilder讀取行資料,通過FileStream和StreamReader處理資料流:
1 public static string ReadTextFromFileWithReadOnlyMode(string filename) 2 { 3 string content; 4 using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 5 { 6 using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default)) 7 { 8 StringBuilder sb = new StringBuilder(); 9 while (!sr.EndOfStream) 10 { 11 sb.AppendLine(sr.ReadLine() + "<br>"); 12 } 13 content = sb.ToString(); 14 } 15 } 16 return content; 17 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/93264.html
標籤:C#
