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

后端 未结 13 851
青春惊慌失措
青春惊慌失措 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:28

    Try this.

    string path = @"E:\AppServ\Example.txt";
    if (!File.Exists(path))
    {
        using (var txtFile = File.AppendText(path))
        {
            txtFile.WriteLine("The very first line!");
        }
    }
    else if (File.Exists(path))
    {     
        using (var txtFile = File.AppendText(path))
        {
            txtFile.WriteLine("The next line!");
        }
    }
    

提交回复
热议问题