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 字符输出。

posted @ 2011-06-22 14:11  meil  阅读(823)  评论(0编辑  收藏  举报