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
Why is File.Open so much better than File.Create for overwriting an existing file?
提问by Erich Mirabal
This is in relation to this other SO questionwhich 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
.
在我写这个问题时,结果是 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
Open
overCreate
?
是否有什么我失踪的这些方,这将使清楚这更好的选择
Open
了Create
?
采纳答案by Samuel
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.
对我来说,我确切地知道File.Open("...", FileMode.Create)
做什么,因为我可以将鼠标悬停在上面FileMode.Create
,它告诉我每次都会创建一个新文件。File.Create("...")
没有这样的工具提示表明它会这样做。
回答by Andrew Hare
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.
好吧,我也回答了Create
但Open
确实是更好的解决方案,因为您表示您希望打开一个文件,并且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.Open
reads 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。如果你想创建和打开一个文件,第一个更明确。