Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

text-files

People also ask

Does append create a file if it doesn't exist?

Create file if it does not exist by Using append modeIf the file does not exist, it creates a new file for reading and writing. It will not truncate the file and append the content at end of the file as shown in the example below.

Which mode creates a new file if the file doesn't exists?

"w" - Write - will create a file if the specified file does not exist.

Does StreamWriter create file if not exist?

Creating a StreamWriterIf the file does not exist, it will be created. If it does exist, the old file will be overwritten.

Which command create and import a file if file does not exist?

The touch command will do this nicely.


Use the correct constructor:

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

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

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

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

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

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

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