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

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

贱贱哒 发布于 2021-11-25 字数 781 浏览 857 回复 4 原文

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?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


难理解 2022-06-07 4 楼

First, I think you might be reading too much into it. I, for instance, I tend to up-vote the first correct answer, and neglect any further answers... so getting there first helps a bit.

Second, File.Open reads better than System.IO.File.Open, even though they are the same.

Third, Create is not as semantically relevant as Open, from a readability standpoint. If you want to create AND open a file, the first is more explicit.

死开点丶别碍眼 2022-06-07 3 楼

Well, I too answered with Create but Open really is the better solution as you are indicating that you wish to open a file and with the FileMode.Create you are indicating that you wish to create the file if it does not already exist. I think that is pretty clear.

一页 2022-06-07 2 楼

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!

清醇 2022-06-07 1 楼

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.