11

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
  • The .NET wrapper exposes everything that the underlying winapi function (CreateFile) is capable of. You can have a very productive programming career without ever using everything. Accidents do happen. Commented Oct 13, 2020 at 11:32
  • 1
    "what is the difference"? well, you wrote it in your question: "Truncate doesn't create a new file". when do you use it: when you want to overwrite the content of a file, but don't want to create it if it doesn't already exists. Commented Oct 13, 2020 at 15:14

2 Answers 2

17

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

2
  • 1
    But why should you use it then? You could stick with File.Create Commented Oct 13, 2020 at 10:51
  • 7
    For the same reason that you would use Single(), instead of First(). If your logic assumes that file should exist, it's better to use FileMode.Truncate to get notified that it doesn't and there is a problem somewhere
    – maxc137
    Commented Oct 13, 2020 at 10:53
0

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
    }
}
1
  • 4
    FileMode.Create achieves the same thing as fileInfo.Exists ? FileMode.Truncate : FileMode.CreateNew (doc)
    – maxc137
    Commented Mar 23, 2022 at 10:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.