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

转自: 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);  

运行。。。没效果如,呵呵,直接追加进去了,点击文本即可看到效果了。