C# 生成txt问题

来源:百度知道 编辑:UC知道 时间:2024/06/07 16:23:12
要求生成一个txt文件,如果路径下文件名不存在,写入txt内容;如果文件名存在,打开存在的txt文件,写入加上新的txt内容。部分代码如下:(path为文件名路径,else部分没有什么问题,if的部分请哪位看看怎么写)
if (File.Exists(path))
{

}
else
{
using (FileStream fs = File.Create(path, 1024))
{
StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("UTF-8"));
string content="123456789";
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
}

string path="1.txt";
System.IO.StreamWriter objwrite = new System.IO.StreamWriter(path, true);
objwrite.WriteLine("woaini");
objwrite.Close();

记住(path, true);这两个参数的第二个是true,他的意思就是写在这个文件的末尾,假如是false的话会把此文件重写

StreamWriter 有现成的构造函数可以用。
StreamWriter (string path,bool apend);
所有你只要加上
StreamWriter sw = new StreamWriter(fs,true,System.Text.Encoding.GetEncoding("UTF-8")); 就可以了