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.
"w" - Write - will create a file if the specified file does not exist.
Creating a StreamWriterIf the file does not exist, it will be created. If it does exist, the old file will be overwritten.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With