在 C# 中创建一个空文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/802541/
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:47:51  来源:igfitidea点击:

Creating an empty file in C#

c#.net

提问by Paul Hollingsworth

What's the simplest/canonical way to create an empty file in C#/.NET?

在 C#/.NET 中创建空文件的最简单/规范的方法是什么?

The simplest way I could find so far is:

到目前为止,我能找到的最简单的方法是:

System.IO.File.WriteAllLines(filename, new string[0]);

采纳答案by Jon Skeet

Using just File.Createwill leave the file open, which probably isn't what you want.

使用 justFile.Create将使文件保持打开状态,这可能不是您想要的。

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 Disposedirectly:

或者直接调用Dispose

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 Disposedirectly instead of using a usingstatement doesn't really make much difference here as far as I can tell - the only way it couldmake a difference is if the thread were aborted between the call to File.Createand the call to Dispose. If that race condition exists, I suspect it would alsoexist in the usingversion, if the thread were aborted at the very end of the File.Createmethod, just before the value was returned...

请注意,据我所知,Dispose直接调用而不是使用using语句在这里并没有太大区别 - 唯一可以产生影响的方法是线程是否在调用File.Create和调用之间中止Dispose。如果那场比赛条件存在,我怀疑这会存在于using版本,如果线程均在的最后中止File.Create方法,返回值之前...

回答by Eoin Campbell

System.IO.File.Create(@"C:\Temp.txt");

As others have pointed out, you should dispose of this object or wrap it in an empty using statement.

正如其他人指出的那样,您应该处理此对象或将其包装在一个空的 using 语句中。

using (System.IO.File.Create(@"C:\Temp.txt"));

回答by Tamas Czinege

File.WriteAllText("path", String.Empty);

or

或者

File.CreateText("path").Close();

回答by Crippledsmurf

Path.GetTempFileName() will create a uniquly named empty file and return the path to it.

Path.GetTempFileName() 将创建一个唯一命名的空文件并返回它的路径。

If you want to control the path but get a random file name you can use GetRandomFileName to just return a file name string and use it with Create

如果您想控制路径但获得随机文件名,您可以使用 GetRandomFileName 仅返回文件名字符串并将其与 Create 一起使用

For example:

例如:

string fileName=Path.GetRandomFileName();
File.Create("custom\path\" + fileName);

回答by umilmi81

You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.

您可以将方法从返回的对象中链接出来,因此您可以立即关闭您在单个语句中打开的文件。

File.Open("filename", FileMode.Create).Close();

回答by aggieNick02

A somewhat common use case for creating an empty file is to trigger something else happening in a different process in the absence of more sophisticated in process communication. In this case, it can help to have the file creation be atomic from the outside world's point of view (particularly if the thing being triggered is going to delete the file to "consume" the trigger).

创建空文件的一个常见用例是在没有更复杂的进程通信的情况下触发不同进程中发生的其他事情。在这种情况下,从外部世界的角度来看,文件创建是原子的会有所帮助(特别是如果被触发的事情将删除文件以“消耗”触发器)。

So it can help to create a junk name (Guid.NewGuid.ToString()) in the same directory as the file you want to create, and then do a File.Move from the temporary name to your desired name. Otherwise triggered code which checks for file existence and then deletes the trigger may run into race conditions where the file is deleted before it is fully closed out.

因此它可以帮助在与您要创建的文件相同的目录中创建一个垃圾名称 (Guid.NewGuid.ToString()),然后从临时名称执行 File.Move 到您想要的名称。否则,检查文件存在然后删除触发器的触发代码可能会遇到竞争条件,即文件在完全关闭之前被删除。

Having the temp file in the same directory (and file system) gives you the atomicity you may want. This gives something like.

将临时文件放在同一目录(和文件系统)中可为您提供您可能想要的原子性。这给出了类似的东西。

public void CreateEmptyFile(string path)
{
    string tempFilePath = Path.Combine(Path.GetDirectoryName(path),
        Guid.NewGuid.ToString());
    using (File.Create(tempFilePath)) {}
    File.Move(tempFilePath, path);
}

回答by Phil Haselden

To avoid accidentally overwriting an existing file use:

为避免意外覆盖现有文件,请使用:

using (new FileStream(filename, FileMode.CreateNew)) {}

...and handle the IOException which will occur if the file already exists.

...并处理如果文件已经存在将发生的 IOException。

File.Create, which is suggested in other answers, will overwrite the contents of if the file already exists. In simple cases you could mitigate this using File.Exists(). However something more robust is necessary in scenarios where multiple threads and/or processes are attempting to create files in the same folder simultaneously.

File.Create,在其他答案中建议,如果文件已经存在,将覆盖 的内容。在简单的情况下,您可以使用File.Exists(). 然而,在多个线程和/或进程试图同时在同一文件夹中创建文件的情况下,需要更强大的东西。