我有一个c#程序的字符串,我想写一个文件,总是覆盖现有的内容。如果文件不存在,程序应该创建一个新文件,而不是抛出异常。


System.IO.File.WriteAllText (@"D:\path.txt", contents);

如果文件存在,这将覆盖它。 如果文件不存在,则创建该文件。 请确保您拥有在该位置写入的适当权限,否则将会出现异常。


使用文件。WriteAllText方法。如果文件不存在,则创建该文件;如果文件存在,则覆盖该文件。


如果您的代码不要求首先截断文件,您可以使用FileMode。OpenOrCreate打开文件流,如果文件不存在将创建文件,如果文件存在则打开文件。您可以使用流指向前面并开始覆盖现有文件?

我假设这里用的是流,还有其他方法来写文件。


一般来说,FileMode。创造是你所追求的。


使用文件模式enum来更改文件。开放的行为。这既适用于二进制内容,也适用于文本。

因为FileMode。打开和文件模式。OpenOrCreate加载现有的内容到文件流,如果你想完全替换文件,你需要首先清除现有的内容,如果有,在写入流之前。FileMode。Truncate自动执行此步骤

// OriginalFile:
oooooooooooooooooooooooooooooo

// NewFile:
----------------

// Write to file stream with FileMode.Open:
----------------oooooooooooooo
var exists = File.Exists(path);
var fileMode = exists
    ? FileMode.Truncate   // overwrites all of the content of an existing file
    : FileMode.CreateNew  // creates a new file

using (var destinationStream = File.Open(path, fileMode)
{
    await newContentStream.CopyToAsync(destinationStream);
}

FileMode Enum