在C#/ .NET中创建空文件的最简单/规范方法是什么?
到目前为止我能找到的最简单的方法是:
System.IO.File.WriteAllLines(filename, new string[0]);
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 362
使用just File.Create会使文件保持打开状态,这可能不是你想要的.
你可以使用:
using (File.Create(filename)) ;
Run Code Online (Sandbox Code Playgroud)
看起来有点奇怪,请注意.您可以使用大括号:
using (File.Create(filename)) {}
Run Code Online (Sandbox Code Playgroud)
或者直接打电话Dispose:
File.Create(filename).Dispose();
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,如果您打算在多个地方使用它,您应该考虑将其包装在辅助方法中,例如
public static void CreateEmptyFile(string filename)
{
File.Create(filename).Dispose();
}
Run Code Online (Sandbox Code Playgroud)
请注意,就我所知,Dispose直接调用而不是使用using语句并没有太大的区别 - 它可以产生影响的唯一方法是在调用File.Create和调用之间中断线程Dispose.如果存在该竞争条件,我怀疑它在版本中也会存在using,如果该线程在File.Create方法的最后被中止,就在返回值之前...
Tam*_*ege 32
File.WriteAllText("path", String.Empty);
Run Code Online (Sandbox Code Playgroud)
要么
File.CreateText("path").Close();
Run Code Online (Sandbox Code Playgroud)
Eoi*_*ell 20
System.IO.File.Create(@"C:\Temp.txt");
Run Code Online (Sandbox Code Playgroud)
正如其他人指出的那样,你应该处理这个对象或将它包装在一个空的using语句中.
using (System.IO.File.Create(@"C:\Temp.txt"));
Run Code Online (Sandbox Code Playgroud)
为避免意外覆盖现有文件,请使用:
using (new FileStream(filename, FileMode.CreateNew)) {}
Run Code Online (Sandbox Code Playgroud)
...并处理如果文件已经存在将发生的 IOException。
File.Create,这是在其他答案中建议的,如果文件已经存在,它将覆盖文件的内容。在简单的情况下,您可以使用File.Exists(). 然而,在多个线程和/或进程试图同时在同一文件夹中创建文件的情况下,需要更强大的东西。