我閱讀了多個論壇和解決方案,但沒有人幫助我解決問題。請讓我知道下面一段代碼中的缺陷。系統IO異常無法訪問,因爲已被其他進程使用
public static void WriteLogFile(string writedata)
{
string path = @"C:\Example.txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(writedata);
//tw.Close();
}
else if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(writedata);
//tw.Close();
}
}
}
爲什麼你使用''else if''塊中使用()''而不是''if''? –
變化'File.Create(路徑);''來File.Create(路徑).Dispose();' – Equalsk
@Equalsk或只是刪除線作爲一個整體,StreamWriter的將創建該文件,如果它不存在 –