看来问题在于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