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

前端 未结 8 816
南笙
南笙 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条回答
  • Pass true as the append parameter of the constructor:

    TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-15 18:21

    Change your constructor to pass true as the second argument.

    TextWriter tsw = new StreamWriter(@"C:\Hello.txt", true);
    
    0 讨论(0)
  • 2020-12-15 18:21

    Best thing is

    File.AppendAllText("c:\\file.txt","Your Text");
    
    0 讨论(0)
  • 2020-12-15 18:23
    using (StreamWriter writer = File.AppendText(LoggingPath))
    {
        writer.WriteLine("Text");
    }
    
    0 讨论(0)
  • 2020-12-15 18:28

    First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText. For more info check the code below.


    string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt"; 
    string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;
    
    
     if (!File.Exists(str_Path))
     {
         File.Create(str_Path).Close();
        File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
    
     }
     else if (File.Exists(str_Path))
     {
    
         File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
    
     }
    
    0 讨论(0)
提交回复
热议问题