Archive for April 26th, 2008
Make a file empty
Found someone using Google to figure out how to clear out the contents of a file and hitting my blog. Well, it’s pretty easy - use FileMode.Truncate when opening the file.
using (FileStream fs = File.Open(filepath, FileMode.Truncate, FileAccess.Write))
{
// Code to write to the file goes here
fs.Close();
}
Which one is faster - FileStream.Position or FileStream.Seek?
FileStream.Position property is implemented in terms of File.Seek (essentially File.Seek(value, SeekOrigin.Begin)). Consequently setting the location of the virtual file-pointer by calling Seek directly instead of calling Position results in slightly faster execution speed. Seek is also better because it has more options.