It seems that the problem is that kind of a File.Exists()
check is done internally, which fails if the file is hidden (e.g. tries to do a FileMode.Create
on a file which already exists).
Therefore, use FileMode.OpenOrCreate
to make sure that the file is opened or created even if it is hidden, or just FileMode.Open
if you do not want to create it if it doesn't exist.
When FileMode.OpenOrCreate
is used though, the file will not be truncated, so you should set its length at the end to make sure that there is no leftover after the end of the text.
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);
}
}
If you use .NET 4.5 or later, there is a new overload which prevents the disposal of the StreamWriter
to also dispose the underlying stream. The code could then be written slighly more intuitively like this:
using (FileStream fs = new FileStream(filename, FileMode.Open)) {
using (TextWriter tw = new StreamWriter(fs, Encoding.UTF8, 1024, true)) {
// 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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…