您的位置:首页 > 编程语言 > C#

C# FileStream Write追加写入文本(转载)

2015-04-13 11:25 399 查看
转自: http://blog.csdn.net/andrew_wx/article/details/6629913
该例子为追加 C盘中的 file1.txt 的文本内容

完整代码如下:

引入命名空间:

using System.IO;


完整代码:

namespace FileStreamWrite
{
class Program
{
static void Main(string[] args)
{
FileStream fs = null;
string filePath = "C:\\file1.txt";
//将待写的入数据从字符串转换为字节数组
Encoding encoder = Encoding.UTF8;
byte[] bytes = encoder.GetBytes("Hello World! \n\r");
try
{
fs = File.OpenWrite(filePath);
//设定书写的开始位置为文件的末尾
fs.Position = fs.Length;
//将待写入内容追加到文件末尾
fs.Write(bytes, 0, bytes.Length);
}
catch (Exception ex)
{
Console.WriteLine("文件打开失败{0}", ex.ToString());
}
finally
{
fs.Close();
}
Console.ReadLine();
}
}
}


代码中

fs = File.OpenWrite(filePath);
//设定书写的开始位置为文件的末尾
fs.Position = fs.Length;

等效于

fs = File.Open(filePath, FileMode.Append, FileAccess.ReadWrite);


运行。。。没效果如,呵呵,直接追加进去了,点击文本即可看到效果了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: