zoukankan      html  css  js  c++  java
  • C#中基于FileStream的文本文件读写操作

     1 using System;
     2 using System.Collections.Generic;
     3 using System.IO;
     4 using System.Linq;
     5 using System.Text;
     6 using System.Threading.Tasks;
     7 
     8 namespace ConsoleApp
     9 {
    10     class Program
    11     {
    12         static void Main(string[] args)
    13         {
    14             FileStreamRead();
    15 
    16             //FileStreamWrite();
    17 
    18 
    19             Console.ReadKey();
    20         }
    21 
    22         private static void FileStreamWrite()
    23         {
    24             FileStream fs = new FileStream(@".
    es	est2.txt", FileMode.Create, FileAccess.Write);
    25             byte[] bs = Encoding.UTF8.GetBytes(@"你好");
    26             fs.Write(bs, 0, bs.Length);
    27             fs.Close();
    28             fs.Dispose();
    29             Console.WriteLine("<" + Encoding.UTF8.GetString(bs, 0, bs.Length) + ">" + "已被写入文件!");
    30         }
    31         private static void FileStreamRead()
    32         {
    33             FileStream fs = new FileStream(@".
    es	est.txt", FileMode.Open, FileAccess.Read);
    34             byte[] buff = new byte[1024];
    35             int len = fs.Read(buff, 0, 1024);
    36             while (len > 0)
    37             {
    38                 string s = Encoding.UTF8.GetString(buff, 0, len);
    39                 Console.WriteLine(s);
    40                 len = fs.Read(buff, 0, 1024);
    41             }
    42         }
    43     }
    44 }
    View Code

    上面就是使用FileStream读写文本文件的代码,很简单,但有些细节值得注意。

    1,我的文件路径使用的是@". es est.txt",在解决方案资源管理器视图中如下:

      

      “.”代表程序运行的当前目录,如果直接拷贝代码,并复制上图的项目文件夹结构,调试运行可能报错,因为在程序的运行目录下没有对应的资源。

      解决办法是右键要用到的资源文件,打开属性选项,做如下图设置:

      

      再重新编译项目即可。这时打开项目所在文件夹,进入bin目录,你会发现在Debug或是Release(取决你调试运行程序的选项)目录下出现了一个res文件夹,

      打开,里面会有一个test.txt文件。

      

      在控制台应用和winform应用开发中,经常会遇到上面这种情况。

    2,还有一点,在使用FileStream这类对象时,要注意对象和资源的释放和回收,FileStream对象使用完后要调用一下close()方法和dispose()方法,或者使用using子句。

    当然以上只是文件读写操作里的最基本情况,其他更深入的使用细节可以参考msdn文档继续研究。

  • 相关阅读:
    无法通过给定的扩展名确定设备类型
    biuld example_osgviewerGLUT遇到的error Link2019
    OpenGL渲染流水线
    设计模式总目录
    删除thumbs.db是提示正在使用
    COM技术内幕第十章笔记EXE中的服务器
    在高低版本之间互导max文件,以fbx格式为载体尤佳。
    参数值传递的本质
    VS 为什么要检查行尾的一致性?
    vs2005中的GL文件
  • 原文地址:https://www.cnblogs.com/Lightmen/p/5539513.html
Copyright © 2011-2022 走看看