高分求C#中关于文件的问题

来源:百度知道 编辑:UC知道 时间:2024/05/20 22:46:46
是这样的,我的程序要实现一个功能,先判断D盘中有没有test.txt这个文件,要是有就在它里面写上“我 爱 C#”这句话,(如果原来有一句,那么就换行在写一句。就是不能覆盖原来的句子)。要是不存在,那么就在D盘创建一个test.txt文件,写上这句话。
跪求!
一楼和三楼:
“AppendAllText”方法没有采用“1”个参数的重载

但是把AppendAllText改为AppendText就能解决了。同样谢谢二楼。你的方法我认真考虑了,但是我认为不能达到结果!

StreamWriter sw;
if (File.Exists("D:\\text.txt"))
{
sw = File.AppendAllText("D:\\text.txt");
}
else
{
sw = new StreamWriter("D:\\text.txt");
}
sw.WriteLine("我 爱 C#");
sw.Close();

如果严格按照你的想法的话如下:
使用前要在最开始添加:
using System.IO;

string filepath = "d:\\test.txt";
string str="我 爱 C#";
if (File.Exists(filepath))
{
StreamWriter sw = new StreamWriter(filepath,true,Encoding.Default);
sw.WriteLine(str);
sw.Close();
}
else
{
StreamWriter sw = new StreamWriter(filepath,true, Encoding.Default);
sw.WriteLine(str);
sw.Close();
}如果只是实现你的功能,则:
string filepath = "d:\\test.txt";
string str="我