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 展开
如果a.txt存在,在其已有的内容后面写入abcdefg,如果a.txt不存在,新建a.txt文件,然后写入abcdefg 展开
展开全部
楼主好懒,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);
}
}
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);
}
}
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询