• C# FileStream Write追加写入文本


    该例子为追加 C盘中的 file1.txt 的文本内容

    完整代码如下:

    引入命名空间:

    [csharp] view plain copy
     print?
    1. using System.IO;  

    完整代码:

    [csharp] view plain copy
     print?
    1. namespace FileStreamWrite  
    2. {  
    3.     class Program  
    4.     {  
    5.         static void Main(string[] args)  
    6.         {  
    7.             FileStream fs = null;  
    8.             string filePath = "C:\file1.txt";  
    9.             //将待写的入数据从字符串转换为字节数组  
    10.             Encoding encoder = Encoding.UTF8;  
    11.             byte[] bytes = encoder.GetBytes("Hello World!  ");  
    12.             try  
    13.             {  
    14.                 fs = File.OpenWrite(filePath);  
    15.                 //设定书写的开始位置为文件的末尾  
    16.                 fs.Position = fs.Length;  
    17.                 //将待写入内容追加到文件末尾  
    18.                 fs.Write(bytes, 0, bytes.Length);  
    19.             }  
    20.             catch (Exception ex)  
    21.             {  
    22.                 Console.WriteLine("文件打开失败{0}", ex.ToString());  
    23.             }  
    24.             finally  
    25.             {  
    26.                 fs.Close();  
    27.             }  
    28.             Console.ReadLine();  
    29.         }  
    30.     }  
    31. }  


    以上为完整代码!


    代码中

    [csharp] view plain copy
     print?
    1. fs = File.OpenWrite(filePath);  
    2. //设定书写的开始位置为文件的末尾  
    3. fs.Position = fs.Length;  
    等效于

    [csharp] view plain copy
     print?
    1. fs = File.Open(filePath, FileMode.Append, FileAccess.ReadWrite);  

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


  • 相关阅读:
    codeforce 148D. Bag of mice[概率dp]
    poj2096 Collecting Bugs[期望dp]
    poj3744 Scout YYF I[概率dp+矩阵优化]
    hdu 5318 The Goddess Of The Moon
    hdu5411 CRB and Puzzle[矩阵优化dp]
    poj3734 Blocks[矩阵优化dp or 组合数学]
    1948 NOI 嘉年华
    教主泡嫦娥[有趣的dp状态设计]
    HDU 4455 Substrings[多重dp]
    1296: [SCOI2009]粉刷匠[多重dp]
  • 原文地址:https://www.cnblogs.com/alan666/p/8312188.html
Copyright © 2020-2023  润新知