Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is File.Open so much better than File.Create for overwriting an existing file?

Tags:

c#

file

This is in relation to this other SO question which asks how to overwrite an existing file.

The top answer is this:

FileStream file = File.Open("text.txt", FileMode.Create);

My answer was this:

FileStream fs = System.IO.File.Create(fileName);

As of when I wrote this question, the tally was 14-0 in favor of Open.

If votes are an indication of good versus bad solutions, this makes me wonder a bit:

Is there something I'm missing in these methods that would make it clearly that much better to choose Open over Create?

like image 300
Erich Mirabal Avatar asked Apr 27 '09 14:04

Erich Mirabal


People also ask

What does it mean to overwrite an existing file?

overwrite verb (REPLACE) If you overwrite a computer file, you replace it with a different one.

How do I overwrite an existing file?

Save As -> Replace File If you are accustomed to selecting "File -> Save As" when saving documents, you can also overwrite the file with your changes this way. Select "Replace File. This is the same behavior as File Save." The original file will be overwritten.

What mode overwrite existing text in a file?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it.

What happens when you replace files?

If you choose Replace, the original file will be overwritten. But here's an important thing to note: overwriting a file on Mac doesn't mean you immediately delete the data it references. When you hit that Replace button, you basically delete the name of the file, thumbnails, and the icon.


2 Answers

To me, I know exactly what File.Open("...", FileMode.Create) does because I can hover over FileMode.Create and it tells me that is will create a new file each time. File.Create("...") has no such tool tip that indicates that it will do this.

like image 87
Samuel Avatar answered Oct 19 '22 21:10

Samuel


There only one place I know you could look for an answer to this one: Reflector

And it turns out both call new FileStream(... with a full set of arguments!

like image 29
Stijn Sanders Avatar answered Oct 19 '22 20:10

Stijn Sanders