• C# FileStream StreamWrite追加到文本文件末尾


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

    完整代码例如以下:

    引入命名空间:

    [csharp] view plaincopyprint?
     
    1. using System.IO;  

    完整代码:

    [csharp] view plaincopyprint?
     
    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! \n\r");  
    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 plaincopyprint?
     
    1. fs = File.OpenWrite(filePath);  
    2. //设定书写的開始位置为文件的末尾  
    3. fs.Position = fs.Length;  

    等价于

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

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

    若以上代码编译有问题,可下载项目文件直接编译: http://download.csdn.net/source/3465946

  • 相关阅读:
    路由器、交换机学习之IP地址、使用网络掩码划分子网
    PCB线宽与电流计算器--在线计算
    数组的访问形式
    STM32开发环境--使用MDK建立一个工程
    电源模块PCB设计
    STM32--TIM定时器时钟分割(疑难)
    STM32——输入捕获实验原理及配置步骤
    STM32——PWM基本知识及配置过程
    STM32——通用定时器基本定时功能
    STM32——NVIV:嵌套中断向量控制器
  • 原文地址:https://www.cnblogs.com/mfryf/p/3138575.html
Copyright © 2020-2023  润新知