How to write data to a text file without overwriting the current data

前端 未结 8 877
南笙
南笙 2020-12-15 18:00

I can\'t seem to figure out how to write data to a file without overwriting it. I know I can use File.appendtext but I am not sure how to plug that into my syntax. Here is m

8条回答
  •  醉酒成梦
    2020-12-15 18:18

    Here's a chunk of code that will write values to a log file. If the file doesn't exist, it creates it, otherwise it just appends to the existing file. You need to add "using System.IO;" at the top of your code, if it's not already there.

    string strLogText = "Some details you want to log.";
    
    // Create a writer and open the file:
    StreamWriter log;
    
    if (!File.Exists("logfile.txt"))
    {
      log = new StreamWriter("logfile.txt");
    }
    else
    {
      log = File.AppendText("logfile.txt");
    }
    
    // Write to the file:
    log.WriteLine(DateTime.Now);
    log.WriteLine(strLogText);
    log.WriteLine();
    
    // Close the stream:
    log.Close();
    

提交回复
热议问题