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

前端 未结 8 865
南笙
南笙 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: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);
    
     }
    

提交回复
热议问题