什么是最简单的/典型的方法来创建在C#中一个空文件/。NET?
我能找到到目前为止,最简单的方法是:
System.IO.File.WriteAllLines(文件名,新的字符串[0]);
解决方案
只需使用 File.Create
将离开文件打开,这可能是不是你想要的。
您可以使用:
使用(File.Create(文件名));
这看起来有点奇怪,你要知道。你可以使用大括号来代替:
使用(File.Create(文件名)){}
或者就叫处置
直接:
File.Create(文件名).Dispose();
无论哪种方式,如果你打算使用这个在多个地方,你或许应该考虑包装在一个辅助方法,如:
公共静态无效CreateEmptyFile(字符串文件名)
{
File.Create(文件名).Dispose();
}
请注意,调用处置
,而不是直接使用使用
声明中并没有真正太大的区别就在这里就我所知道的 - 只有这样,它的可以的有所作为的是,如果线程被调用的夭折而 File.Create
和调用处置
。如果那场比赛条件存在,我怀疑这会的也的存在于使用
的版本,如果线程被中止,在 File.Create 法,该值返回之前...
What's the simplest/canonical way to create an empty file in C#/.NET?
The simplest way I could find so far is:
System.IO.File.WriteAllLines(filename, new string[0]);
解决方案
Using just File.Create
will leave the file open, which probably isn't what you want.
You could use:
using (File.Create(filename)) ;
That looks slightly odd, mind you. You could use braces instead:
using (File.Create(filename)) {}
Or just call Dispose
directly:
File.Create(filename).Dispose();
Either way, if you're going to use this in more than one place you should probably consider wrapping it in a helper method, e.g.
public static void CreateEmptyFile(string filename)
{
File.Create(filename).Dispose();
}
Note that calling Dispose
directly instead of using a using
statement doesn't really make much difference here as far as I can tell - the only way it could make a difference is if the thread were aborted between the call to File.Create
and the call to Dispose
. If that race condition exists, I suspect it would also exist in the using
version, if the thread were aborted at the very end of the File.Create
method, just before the value was returned...