我想製作一個簡單的軟件,它將數據存儲在TXT日誌文件中。 這是我的代碼FileStream.WriteLine()不寫入文件
FileStream fs = null;
StreamWriter fw = null;
try
{
fs= new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+"/textme.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
fw = new StreamWriter(fs);
fw.Write("sadadasdsadsadsadas");
for (int i = 0; i < AnimalShelter.AnimalList.Count; i++)
{
fw.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
Console.WriteLine("<chipNr>" + AnimalShelter.AnimalList[i].ChipRegistrationNumber + "<chipNr>");
}
}
catch(IOException)
{
MessageBox.Show("ERROR THROWN");
}
finally
{
if (fs!= null) fs.Close();
// if (fw != null) fw.Close();
}
我取得了什麼是:文件被創建,但沒有被寫在上面。 我查了很多帖子,但找不到任何特別的幫助。
首先,不需要在try/finally塊,你可以使用'使用'代替。 – antonijn 2013-03-16 18:18:10
您可能需要刷新StreamWriter:'fw.Flush()' – 2013-03-16 18:18:12
StreamWriter具有一個構造函數,它接受一個字符串,該文件的路徑和一個布爾值,設置爲true以追加。它會幫助你陷入成功的陷阱。 – 2013-03-16 18:33:56