C# 为什么 File.Open 在覆盖现有文件方面比 File.Create 好得多?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/793753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:24:52  来源:igfitidea点击:

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

c#file

提问by Erich Mirabal

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

这与另一个 SO问题有关,该问题询问如何覆盖现有文件。

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.

在我写这个问题时,结果是 14-0 支持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 Openover Create?

是否有什么我失踪的这些方,这将使清楚这更好的选择 OpenCreate

采纳答案by Samuel

To me, I know exactly what File.Open("...", FileMode.Create)does because I can hover over FileMode.Createand 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.

对我来说,我确切地知道File.Open("...", FileMode.Create)做什么,因为我可以将鼠标悬停在上面FileMode.Create,它告诉我每次都会创建一个新文件。File.Create("...")没有这样的工具提示表明它会这样做。

回答by Andrew Hare

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

好吧,我也回答了CreateOpen确实是更好的解决方案,因为您表示您希望打开一个文件,并且FileMode.Create您表示您希望创建该文件(如果该文件尚不存在)。我认为这很清楚。

回答by Brian Genisio

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.Openreads better than System.IO.File.Open, even though they are the same.

其次,File.Open读起来比 好System.IO.File.Open,即使它们是一样的。

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.

第三,从可读性的角度来看,Create 在语义上不如 Open。如果你想创建和打开一个文件,第一个更明确。

回答by Stijn Sanders

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!

事实证明,这两个调用都new FileStream(...带有完整的参数集!