C#如何将一段文本写入到一个文本文件中?

文件名为a.txt,文本内容为abcdefg,文件a.txt需要保存到的路径为D:\folder\如果a.txt存在,在其已有的内容后面写入abcdefg,如果a.txt... 文件名为a.txt,文本内容为abcdefg,文件a.txt需要保存到的路径为D:\folder\

如果a.txt存在,在其已有的内容后面写入abcdefg,如果a.txt不存在,新建a.txt文件,然后写入abcdefg
展开
 我来答
四分之三月台
推荐于2018-04-11
知道答主
回答量:15
采纳率:0%
帮助的人:12.2万
展开全部
楼主好懒,MSDN里面搜System.IO里面就有了

class Test
{

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}

//Create the file.
using (FileStream fs = File.Create(path))
{
AddText(fs, "This is some text");
AddText(fs, "This is some more text,");
AddText(fs, "\r\nand this is on a new line");
AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n");

for (int i=1;i < 120;i++)
{
AddText(fs, Convert.ToChar(i).ToString());

}
}

//Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}

private static void AddText(FileStream fs, string value)
{
byte[] info = new UTF8Encoding(true).GetBytes(value);
fs.Write(info, 0, info.Length);
}
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式