C# FileStream/StreamWriter/StreamReader的区别

FileStream对象表示在磁盘或网络路径上指向文件的流。 这个类提供了在文件中读写字节的方法但经常使用StreamReader或 StreamWriter执行这些功能。这是因为 FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据。这是这两种类的一个重要区别,如果你是准备读取byte数据的话,用StreamReader读取然后用 System.Text.Encoding.Default.GetBytes转化的话,如下,则可能出现数据丢失的情况,如byte数据的个数不对等。因此 操作byte数据时要用FileStream。 string textContent = fileStream.ReadToEnd();byte[] bytes = System.Text.Encoding.Default.GetBytes(textContent);
字符数据易于使用, 但是有些操作,比如随机文件访问(访问文件中间某点的数据),就必须由FileStream对象执行.
其中创建FileStream对象最简单的构造函数如下:
     FileStream file = new FileStream(fileName,FileMode.Member);//默认方式,可读可写
     FileStream file = new FileStream(fileName, FileMode.Member, FileAccess.Member);
     而FileAccess的成员:

成 员

说 明

Read

打开文件,用于只读

Write

打开文件,用于只写

ReadWrite

打开文件,用于读写

对文件进行不是FileAccess枚举成员指定的操作会导致抛出异常。此属性的作用是,基于用户的身份验证级别改变用户对文件的访问权限。

在FileStream构造函数不使用FileAccess枚举参数的版本中,使用默认值FileAccess. ReadWrite。

FileMode枚举成员,使用每个值会发生什么,取决于指定的文件名是否表示已有的文件

成 员

文 件 存 在

文件不存在

Append

打开文件,流指向文件的末尾,只能与枚举FileAccess.Write联合使用

创建一个新文件。只能与枚举FileAccess.Write联合使用

Create

删除该文件,然后创建新文件

创建新文件

CreateNew

抛出异常

创建新文件

Open

打开现有的文件,流指向文件的开头

抛出异常

OpenOrCreate

打开文件,流指向文件的开头

创建新文件

Truncate

打开现有文件,清除其内容。流指向文件的开头,保留文件的初始创建日期

抛出异常

FileStream类操作的是字节和字节数组,而Stream类操作的是字符数据
StreamWriter允许将字符和字符串写入文件,它处理底层的转换,向FileStream对象写入数据。StreamReader也类似。
实例:
  using System;
  using System.Data;
  using System.IO;
  using System.Text;

  /// Summary description for FileReadAndWrite
  public class FileReadAndWrite
 {
     public FileReadAndWrite()
     {
         // TODO: Add constructor logic here
     }
     /// 用FileStream写文件
     public void FileStreamWriteFile(string str)
     {
         byte[] byData;
         char[] charData;
         try
         {
             FileStream nFile = new FileStream("love.txt", FileMode.Create);
             //获得字符数组
             charData = str.ToCharArray();
             //初始化字节数组
             byData = new byte[charData.Length];
             //将字符数组转换为正确的字节格式
             Encoder enc = Encoding.UTF8.GetEncoder();
             enc.GetBytes(charData, 0, charData.Length,byData,0,true);
             nFile.Seek(0, SeekOrigin.Begin);
             nFile.Write(byData, 0, byData.Length);
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
     /// FileStream读取文件
     public string FileStreamReadFile(string filePath)
     {
         byte[] data = new byte[100];
         char[] charData = new char[100];
         try
         {
             FileStream file = new FileStream(filePath, FileMode.Open);
             //文件指针指向0位置
             file.Seek(0, SeekOrigin.Begin);
             //读入两百个字节
             file.Read(data, 0, 200);
             //提取字节数组
             Decoder dec = Encoding.UTF8.GetDecoder();
             dec.GetChars(data, 0, data.Length, charData, 0);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         return Convert.ToString(charData);
     }
     /// StreamWriter写文件
     public void StreamWriterWriteFile()
     {
         try
         {
             FileStream nFile = new FileStream("love.txt", FileMode.CreateNew);
             StreamWriter writer = new StreamWriter(nFile);
 
             writer.WriteLine("I love You!");
             writer.WriteLine("Do you love me!");
             writer.Close();
         }
         catch
         { }
     }
     /// StreamReader读取文件
     public string StreamReaderReadFile()
     {
         string str="";
         try
         {
             FileStream file = new FileStream("love.txt", FileMode.Open);
             StreamReader sr = new StreamReader(file);
             while (sr.ReadLine()!=null)
             {
                str += sr.ReadLine();
            }
            //或者str = sr.ReadToEnd();
            sr.Close();
        }
        catch
        { }
        return str;
    }
}


//转载自 http://blog.sina.com.cn/s/blog_67299aec0100snk4.html

猜你喜欢

转载自blog.csdn.net/yinshuli2008/article/details/50583443