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

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

    You just want to open the file in "append" mode.

    http://msdn.microsoft.com/en-us/library/3zc0w663.aspx

    0 讨论(0)
  • 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!");
        }
    }
    
    0 讨论(0)
  • 2020-11-28 20:29

    You can just use File.AppendAllText() Method this will solve your problem. This method will take care of File Creation if not available, opening and closing the file.

    var outputPath = @"E:\Example.txt";
    var data = "Example Data";
    File.AppendAllText(outputPath, data);
    
    0 讨论(0)
  • 2020-11-28 20:29

    From microsoft documentation, you can create file if not exist and append to it in a single call File.AppendAllText Method (String, String)

    .NET Framework (current version) Other Versions

    Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file. Namespace: System.IO Assembly: mscorlib (in mscorlib.dll)

    Syntax C#C++F#VB public static void AppendAllText( string path, string contents ) Parameters path Type: System.String The file to append the specified string to. contents Type: System.String The string to append to the file.

    AppendAllText

    0 讨论(0)
  • 2020-11-28 20:34
    string path=@"E:\AppServ\Example.txt";
    
    if(!File.Exists(path))
    {
       File.Create(path).Dispose();
    
       using( TextWriter tw = new StreamWriter(path))
       {
          tw.WriteLine("The very first line!");
       }
    
    }    
    else if (File.Exists(path))
    {
       using(TextWriter tw = new StreamWriter(path))
       {
          tw.WriteLine("The next line!");
       }
    }
    
    0 讨论(0)
  • 2020-11-28 20:34
    using(var tw = new StreamWriter(path, File.Exists(path)))
    {
        tw.WriteLine(message);
    }
    
    0 讨论(0)
提交回复
热议问题