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

前端 未结 4 696
离开以前
离开以前 2020-12-04 08:35

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 i

相关标签:
4条回答
  • 2020-12-04 09:13

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

    0 讨论(0)
  • 2020-12-04 09:23

    Generally, FileMode.Create is what you're looking for.

    0 讨论(0)
  • 2020-12-04 09:24

    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?

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

    0 讨论(0)
  • 2020-12-04 09:31
    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.
    0 讨论(0)
提交回复
热议问题