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

C#Text Files

C# Problem Overview


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\Example.txt";
if (!File.Exists(path))
{
    File.Create(path);
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The very first line!");
    tw.Close();
}
else if (File.Exists(path))
{
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The next line!");
    tw.Close(); 
}

But the first line seems to always get overwritten... how can I avoid writing on the same line (I'm using this in a loop)?

I know it's a pretty simple thing, but I never used the WriteLine method before. I'm totally new to C#.

C# Solutions


Solution 1 - C#

Use the correct constructor:

else if (File.Exists(path))
{
    using(var tw = new StreamWriter(path, true))
    {
        tw.WriteLine("The next line!");
    }
}

Solution 2 - C#

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.

Solution 3 - C#

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!");
   }
}

Solution 4 - C#

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(); 

Solution 5 - C#

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");

Solution 6 - C#

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

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

Solution 7 - C#

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);

Solution 8 - C#

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);

Solution 9 - C#

 else if (File.Exists(path)) 
{ 
  using (StreamWriter w = File.AppendText(path))
        {
            w.WriteLine("The next line!"); 
            w.Close();
        }
 } 

Solution 10 - C#

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!");
	}
}

Solution 11 - C#

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

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

Solution 12 - C#

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

Solution 13 - C#

using(var tw = new StreamWriter(path, File.Exists(path)))
{
	tw.WriteLine(message);
}

Solution 14 - C#

.NET Core Console App:

public static string RootDir() => Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, @"..\..\..\"));


string _OutputPath = RootDir() + "\\Output\\" + "MyFile.txt";
if (!File.Exists(_OutputPath))
	File.Create(_OutputPath).Dispose();
using (TextWriter _StreamWriter = new StreamWriter(_OutputPath))
{
	_StreamWriter.WriteLine(strOriginalText);
}


      

Solution 15 - C#

Please note that AppendAllLines and AppendAllText methods only create the file, but not the path. So if you are trying to create a file in "C:\Folder", please ensure that this path exists.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBerker YüceerView Question on Stackoverflow
Solution 1 - C#Daniel HilgarthView Answer on Stackoverflow
Solution 2 - C#drchView Answer on Stackoverflow
Solution 3 - C#AekView Answer on Stackoverflow
Solution 4 - C#John BolingView Answer on Stackoverflow
Solution 5 - C#dubuchaView Answer on Stackoverflow
Solution 6 - C#Ed ManetView Answer on Stackoverflow
Solution 7 - C#Vijay ShaaruckView Answer on Stackoverflow
Solution 8 - C#Matan ShaharView Answer on Stackoverflow
Solution 9 - C#SmackView Answer on Stackoverflow
Solution 10 - C#Asiri JayaweeraView Answer on Stackoverflow
Solution 11 - C#Tom CeuppensView Answer on Stackoverflow
Solution 12 - C#David FawzyView Answer on Stackoverflow
Solution 13 - C#Andreas GusakovView Answer on Stackoverflow
Solution 14 - C#R M Shahidul Islam ShahedView Answer on Stackoverflow
Solution 15 - C#Jaideep DhumalView Answer on Stackoverflow