zoukankan      html  css  js  c++  java
  • C#文件读写初步

    C#中读写文件主要涉及到File,FileInfo,FileStream三个类,它们都是System.IO 的类,StreamReader是用于从流读取和写入流的类,使用之前都需using System.IO。

    先定义一个TXT文档路径: string txtpath = (@"D:\url\livebaby.cn.txt") 要读入这个文档。

    1)File 提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream。

        FileStream fs = File.Open(txtpath, FileMode.Open);


        File可以直接调用各种方法(Open、Delete、Exists等)

        例如: if (File.Exists(txtpath))
                {
                    File.Delete(txtpath);
                }

    2)FileInfo 提供用于创建、复制、删除、移动和打开文件的实例方法,并协助创建 FileStream。

        FileInfo fi = new FileInfo(txtpath); //实例化

        FileStream fs = fi.Open();


    3)FileStream 支持通过其 Seek 方法随机访问文件。默认情况下,FileStream 以同步方式打开文件,但它也支持异步操作。

       利用FileStream 我们可以得到一个文件的Streams,接着就是来读取。

    (4)StreamReader 通过使用 Encoding 进行字符和字节的转换,从 Streams 中读取字符。

        StreamWriter 通过使用 Encoding 将字符转换为字节,向 Streams 写入字符。

        StreamReader sr = new StreamReader(fs);

                string str = null;
                string temp=null;
                while((temp=sr.ReadLine())!=null)
                {
                   str+=" "+temp;
                }

         得到一个字符串,再可以对字符串进行处理。

         TextReader 是 StreamReader 和 StringReader 的抽象基类。抽象 Stream 类的实现用于字节输入和输出,而 TextReader 的实现用于 Unicode 字符输出。

         TextWriter 是 StreamWriter 和 StringWriter 的抽象基类。抽象 Stream 类的实现用于字节输入和输出,而 TextWriter 的实现用于 Unicode 字符输出。

    我来自:向东博客
  • 相关阅读:
    ASP.NET WEB开发,实现上传图片
    使用Word API打开Word文档 ASP.NET编程中常用到的27个函数集
    工资单的编辑与保存
    生成工资表
    系统设置
    空间参考
    Envelope几何对象 Curve对象几何对象 Multipatch几何对象 Geometry集合接口 IGeometryCollection接口
    Polygone对象
    Segment,Path,Ring和Polyline对象
    [Android]使用ActivityGroup来切换Activity和Layout
  • 原文地址:https://www.cnblogs.com/meil/p/2086851.html
Copyright © 2011-2022 走看看