在C#/.NET中创建空文件的最简单和经典的方法是什么?
目前我所找到的最简单的方法是:
System.IO.File.WriteAllLines(filename, new string[0]);
仅使用File.Create
会使文件保持打开状态,这可能不是您想要的。
您可以使用以下代码:
// Results in compiler warning "warning CS0642: Possible mistaken empty statement"
using (File.Create(filename)) ;
看起来有点奇怪,不过也可以使用大括号:
using (File.Create(filename)) {}
或者直接调用Dispose
:
File.Create(filename).Dispose();
无论如何,如果您要在多个地方使用它,您应该考虑将其包装在一个帮助方法中,例如:
public static void CreateEmptyFile(string filename)
{
File.Create(filename).Dispose();
}
Dispose
而不是使用using
语句在这里并没有什么区别,据我所知 - 它唯一可能有区别的方式是如果在线程调用File.Create
和调用Dispose
之间中止。如果存在这种竞争条件,我认为它也会存在于using
版本中,如果线程在File.Create
方法的最后被中止,就在值返回之前...
File.WriteAllText("path", String.Empty);
或者File.CreateText("path").Close();
File.WriteAllText(string, string)
使用“UTF-8编码没有字节顺序标记(BOM)”。如果你仍然看到一个,那可能是WriteAllText或其文档中值得报告的错误。 - HeinziEncoding.UTF8
返回一个输出字节顺序标记(BOM)的编码器。您可以使用new UTF8Encoding(false)
来获取一个不输出BOM的UTF8编码器。 - Daniel CrabtreeWriteAllText
在之前的 .NET 版本中是否真的有所不同。然而,为了更加保险,只需跳过编码部分并使用 File.WriteAllBytes(path, new byte[] { });
即可。 - Jürgen SteinblockSystem.IO.File.Create(@"C:\Temp.txt");
正如其他人所指出的,你应该处理这个对象或将其包装在一个空的using语句中。
using (System.IO.File.Create(@"C:\Temp.txt"));
using (new FileStream(filename, FileMode.CreateNew)) {}
...并处理IOException,如果文件已经存在会发生该异常。
File.Create
在其他回答中被建议使用,如果文件已经存在,它将覆盖文件内容。在简单的情况下,您可以使用File.Exists()
来缓解这个问题。然而,在多个线程和/或进程同时尝试创建同一个文件夹中的文件的情况下,需要更健壮的解决方案。
if (!File.Exists(file)) // then create file
是许多开发人员遵循的反模式。最好执行创建并捕获任何异常,从而使您的代码更加线程安全。 - bytedevFile.Open("filename", FileMode.Create).Close();
public void CreateEmptyFile(string path)
{
string tempFilePath = Path.Combine(Path.GetDirectoryName(path),
Guid.NewGuid.ToString());
using (File.Create(tempFilePath)) {}
File.Move(tempFilePath, path);
}
Path.GetTempFileName()会创建一个唯一命名的空文件并返回其路径。
如果您想控制路径但获取随机文件名,可以使用GetRandomFileName仅返回文件名字符串,并将其与Create一起使用
例如:
string fileName=Path.GetRandomFileName();
File.Create("custom\\path\\" + fileName);
using (File.Create(filename)) ;
,但我喜欢File.Create(filename).Dispose();
的简洁性。 - VadimClose()
也会释放资源。Close()
只是调用Dispose
- 请参见https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/IO/Stream.cs#L234 - Jon Skeetusing (new FileStream(filename, FileMode.CreateNew)) { }
。 - Phil Haselden