[英]Writing text to file from multiple instances of program
當我將信息寫入文件並運行多個程序副本時,我收到此錯誤:
該進程無法訪問文件“C:\\ logs \\ log.txt”,因為它正由另一個進程使用。
代碼是:
// create a writer and open the file
TextWriter tw2 = File.AppendText(@"C:\logs\log.txt");
// write a line of text to the file
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
tw2.Flush();
如何以正確的方式做到這一點?
始終將此類代碼封裝在using
語句中
using(TextWriter tw2 = File.AppendText(@"C:\logs\log.txt"))
{
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
//tw2.Flush(); // No need to flush because close alway flush.
}
using
語句在塊的末尾調用tw2.Close()。
此外,如果您在塊內部獲得異常。
現在,如果您的應用程序的其他實例由於某種原因失敗,則該文件不再被鎖定
使用Mutex類來同步對來自多個進程的日志文件的訪問。 在打開文件之前調用WaitOne並在關閉文件后調用ReleaseMutex (Flush是不夠的,您必須關閉文件或使用關鍵字將其包裝起來,如提及的其他答案)。 互斥鎖名稱應以前綴“Global \\”開頭。
除了法拉盛,你必須Close()
文件。
此外,如果另一個實例正在同時寫入文件,則無法訪問它(直到另一個程序調用Close()
。
關閉當前的writer實例並釋放與writer關聯的所有系統資源
在這種情況下,“系統資源”指的是在您關閉它之前保持鎖定的文件。
每次使用文本編寫器打開文件時都需要關閉。
所以每次操作后都要使用
// create a writer and open the file
TextWriter tw2 = File.AppendText(@"C:\logs\log.txt");
// write a line of text to the file
tw2.WriteLine(Environment.NewLine);
tw2.WriteLine(DateTime.Now + " " + "IN INFOSERVCALLER");
tw2.Flush();
tw2.Close();
之后再嘗試寫一下,不會再造成任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.