What is the difference between FileMode.Create and FileMode.Truncate?

Viewed 3391

I don't really understand it:

FileMode.Create creates a new file if it doesn't exists, or overwrites one if it does.

FileMode.Truncate doesn't create a new file, but deletes the entire content of an existing one, so basically it also overwrites the file.

So why is there even the possibility to do:

public void DoStuff()
{
    using (FileStream fs = File.Open(path, FileMode.Truncate, FileAccess.Write, FileShare.None))
    {
        //Do something
    }
}

When it's enough to do:

public void DoStuff()
{
    using (FileStream fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        //Do something
    }
}

Because both are basically using an empty file to write stuff into it

2 Answers

For FileMode.Truncate file must exist. If it doesn't you'll get an exception. FileMode.Create would create new file in this case.

enter image description here

The question sounds like both options might be needed at the same time:

  • if an old file is there, truncate it;
  • if it is not there, create a new one.

My solution to this:

public void DoStuff()
{
    var fileInfo = new FileInfo(path);
    var fileMode = fileInfo.Exists ? FileMode.Truncate : FileMode.CreateNew;
    using (FileStream fs = File.Open(path, fileMode, FileAccess.Write, FileShare.None))
    {
        //Do something
    }
}
Related