Create a .txt file if doesn't exist, and if it does append a new line

后端 未结 13 793
青春惊慌失措
青春惊慌失措 2020-11-28 19:53

I would like to create a .txt file and write to it, and if the file already exists I just want to append some more lines:

string path = @\"E:\\AppServ\\Examp         


        
相关标签:
13条回答
  • 2020-11-28 20:37
    string path = @"E:\AppServ\Example.txt";
    File.AppendAllLines(path, new [] { "The very first line!" });
    

    See also File.AppendAllText(). AppendAllLines will add a newline to each line without having to put it there yourself.

    Both methods will create the file if it doesn't exist so you don't have to.

    • File.AppendAllText
    • File.AppendAllLines
    0 讨论(0)
  • 2020-11-28 20:42

    You could use a FileStream. This does all the work for you.

    http://www.csharp-examples.net/filestream-open-file/

    0 讨论(0)
  • 2020-11-28 20:47

    File.AppendAllText adds a string to a file. It also creates a text file if the file does not exist. If you don't need to read content, it's very efficient. The use case is logging.

    File.AppendAllText("C:\\log.txt", "hello world\n");
    
    0 讨论(0)
  • 2020-11-28 20:48
     else if (File.Exists(path)) 
    { 
      using (StreamWriter w = File.AppendText(path))
            {
                w.WriteLine("The next line!"); 
                w.Close();
            }
     } 
    
    0 讨论(0)
  • 2020-11-28 20:49

    You don't actually have to check if the file exists, as StreamWriter will do that for you. If you open it in append-mode, the file will be created if it does not exists, then you will always append and never over write. So your initial check is redundant.

    TextWriter tw = new StreamWriter(path, true);
    tw.WriteLine("The next line!");
    tw.Close(); 
    
    0 讨论(0)
  • 2020-11-28 20:50

    When you start StreamWriter it's override the text was there before. You can use append property like so:

    TextWriter t = new StreamWriter(path, true);
    
    0 讨论(0)
提交回复
热议问题