C# 将字符串写入文本文件并确保它始终覆盖现有内容。

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

Write string to text file and ensure it always overwrites the existing content.

c#filetext

提问by leora

I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception.

我有一个带有 C# 程序的字符串,我想将其写入文件并始终覆盖现有内容。如果文件不存在,程序应该创建一个新文件而不是抛出异常。

采纳答案by Hemant

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.
  • 如果文件存在,这将覆盖它。
  • 如果该文件不存在,则创建它。
  • 请确保您有适当的权限在该位置写入,否则您将获得异常。

回答by Guffa

Use the File.WriteAllTextmethod. It creates the file if it doesn't exist and overwrites it if it exists.

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

回答by Spence

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

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

I'm assuming your using a streams here, there are other ways to write a file.

我假设您在这里使用流,还有其他方法可以编写文件。

回答by Thomas Danecker

Generally, FileMode.Createis what you're looking for.

一般来说,FileMode.Create就是你要找的。