看來問題在於File.Exists()
這種檢查是在內部完成的,如果該文件被隱藏(例如,嘗試對已存在的文件執行FileMode.Create
),該檢查將失敗。
因此,使用FileMode.OpenOrCreate
確保文件即使被隱藏也可以打開或創建,或者如果您不想在不存在的情況下創建文件,則只需FileMode.Open
。
當使用FileMode.OpenOrCreate
時,文件不會被截斷,因此您應該在末尾設置其長度,以確保文本結束後沒有剩餘。
using (FileStream fs = new FileStream(filename, FileMode.Open)) {
using (TextWriter tw = new StreamWriter(fs)) {
// Write your data here...
tw.WriteLine("foo");
// Flush the writer in order to get a correct stream position for truncating
tw.Flush();
// Set the stream length to the current position in order to truncate leftover text
fs.SetLength(fs.Position);
}
}
如果您使用.NET 4。5或更高版本,有一個新的過載,防止處置StreamWriter
也處置底層流。該代碼然後可以性能稍微更直觀地這樣寫的:
using (FileStream fs = new FileStream(filename, FileMode.Open)) {
using (TextWriter tw = new StreamWriter(fs, Encoding.UTF8, 1024, false)) {
// Write your data here...
tw.WriteLine("foo");
}
// Set the stream length to the current position in order to truncate leftover text
fs.SetLength(fs.Position);
}
什麼異常? – tadman 2010-02-11 19:10:50
它拋出的異常是什麼? – 2010-02-11 19:11:14
扔什麼異常? – Seth 2010-02-11 19:11:20