• 数据流:所有流式类的(抽象)基类都是System.IO命名空间下的Stream类。Stream类允许通过文件、网络、套接字流动数据。我们可以使加密的数据流动,也可以使数据流缓冲处理。
  • 通过缓冲流动数据的优点是:数据流的来源和目的地没有必要在整个数据流动过程中都保持连接:只是在每次缓冲区被冲刷的时候,两者的连接是可用的就可以了。保持连接是消耗资源的行为,所以缓冲可以改善系统的性能。
  • 可供使用的Stream类:
    FileStream:用来向文件读写数据,它还提供了打开、查找、关闭文件的功能
    NetworkStream:它允许你访问TCP/IP套接字(在System.Net.Socket命名空间)
    MemoryStream:允许用流的方法在内存中建立一个可访问的可扩展的区域,也允许把预分配的内存区域当作流看待
    BufferedStream:实用程序类,可以向一个未缓冲的流增加缓冲
    CryptoStream:实用程序类,位于System.Security.Cryptography命名空间,可以加密或解密传递的信息
  • FileStream类的构造参数
    string path 要访问的文件名称和路径
    FileMode mode 指定文件的打开方式,或新建文件
    FileAccess access 文件的读写权限,如Read(读)、Write(写)、ReadWrite(读写 默认)
    FileShare share 其它进程对正在使用文件的访问权限,如None、Read(默认)、Write、ReadWrite
    int bufferSize 缓冲区大小,通常保持默认的4096 bytes
  • FileMode打开方式枚举
    Append 打开已存在的文件并寻到结尾,或新建一文件
    Create 新建一文件,如果文件已存在,则覆盖
    CreateNew 新建一文件,如果已存在,则抛出IOException
    Open 打开,如果不存在,抛出FileNotFoundException
    OpenOrCreate 打开,如果不存在则新建
    Truncate 打开,并将长度置为0,如果不存在,抛出FileNotFoundException
  • 例:
    FileStream fs = new FileStream( @“C:\temp\Demo.dat“, FileMode.Create, FileAccess.Write );
  • 为了传输文本,建立一个Reader或Writer对象,并把它们附在流上,并在它们中使用方法,如WriteLine()方法。因此可以把Reader和Writer类看做是流和代码之间起交互作用的实用程序类:StreamReader、StreamWriter和BinaryReader、BinaryWriter
  • StreamWriter类使用UTF-8做为默认的编码方案。
  • StreamReader的构造函数参数:
    Stream stream 一个开放的流,如FileStream
    Encoding encoding 编码方案,一般可以使用Encoding.Default
    int bufferSize 缓冲区大小(使用默认即可)
    string path 不指定Stream而指定文件,StreamReader将用后台方式打开一个流并用它从文件读取数据
    bool detect 是否自动检测文件中的编码格式(默认为true)
  • StreamReader的方法:
    Read() 在文本流中读文本符号
    ReadLine() 在流中读一行并以字符串变量的形式返回
    ReadToEnd() 从当前位置到结尾读入一个独立的字符串
    Close() 关闭StreamReader及其下属的流
  • 在OpenFileDialog中,如果需要过滤2种以上的格式,可以在扩展名之间加上分号即可。如:文本文件(*.txt *.rtf)|*.txt;*.rtf|全部文件(*.*)|*.*
  • StringCollection类似一个可扩展的字符串数组,因为事先无法确定数组的数量(文本的行数)
  • 例:
    public void ReadFile()
    {
    if( opdMain.ShowDialog() == DialogResult.OK )
    {
    FileStream fs = new FileStream( opdMain.FileName, FileMode.Open, FileAccess.ReadWrite );
    StreamReader aStreamReader = new StreamReader( fs, Encoding.Default );
    StringCollection stringCollection = new StringCollection();
    string onLine;
    while( ( onLine = aStreamReader.ReadLine() ) != null )
    {
    stringCollection.Add( onLine );
    }
    aStreamReader.Close();
    string[] stringArray = new string[ stringCollection.Count ];
    stringCollection.CopyTo( stringArray, 0 );
    rtfEditor.Lines = stringArray;
    }
    }
posted on 2006-01-20 11:36  shf  阅读(471)  评论(0编辑  收藏  举报