Create a .txt file if doesn't exist, and if it

2019-01-12 23:18发布

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# text-files
12条回答
姐就是有狂的资本
2楼-- · 2019-01-12 23:42
using(var tw = new StreamWriter(path, File.Exists(path)))
{
    tw.WriteLine(message);
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-12 23:51
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.

查看更多
萌系小妹纸
4楼-- · 2019-01-12 23:51

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

查看更多
戒情不戒烟
5楼-- · 2019-01-12 23:55

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(); 
查看更多
Anthone
6楼-- · 2019-01-12 23:55

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");
查看更多
时光不老,我们不散
7楼-- · 2019-01-12 23:56

Use the correct constructor:

else if (File.Exists(path))
{
    using(var tw = new StreamWriter(path, true))
    {
        tw.WriteLine("The next line!");
    }
}
查看更多
登录 后发表回答