[转]C#中FileStream和StreamWriter/StreamReader的区别


原文链接:C#中FileStream和StreamWriter/StreamReader的区别——CSDN

区别#

FileStream 对象表示在磁盘或网络路径上指向文件的流。这个类提供了在文件中读写字节的方法。
但经常使用 StreamReaderStreamWriter 执行这些功能。
这是因为 FileStream 类操作的是字节和字节数组,而 StreamReader 或 StreamWriter 操作的是字符数据。

操作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 打开文件,用于读写(默认)
FileMode枚举成员
成员 文件存在 文件不存在
Append 打开文件,流指向文件的末尾,只能与枚举FileAccess.Write联合使用 创建一个新文件。只能与枚举FileAccess.Write联合使用
Create 删除该文件,然后创建新文件 创建新文件
CreateNew 抛出异常 创建新文件
Open 打开现有的文件,流指向文件的开头 抛出异常
OpenOrCreate 打开文件,流指向文件的开头 创建新文件
Truncate 打开现有文件,清除其内容。流指向文件的开头,保留文件的初始创建日期 抛出异常
/// 用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);
}

BinaryReader与BinaryWriter#

C#中除了字节类型以外,还有许多其它基本数据类型,例如,int 、bool、float 等等。
BinaryReaderBinaryWriter 都从 System.Object 直接派生,这些类型可以让我们从基层流中以简洁的二进制格式读取或写入离散数据类型。

using UnityEngine;  
using System;  
using System.Text;  
using System.IO;  
using System.Collections;  
using System.Collections.Generic;  
  
public class FileOperator : MonoBehaviour 
{  
    void Start () 
    {  
        WriteFile ();  
        ReadFile();  
    }  
  
  	// 读取文件  
    void ReadFile()          
    {  
        FileStream fs = new FileStream ("D:\\MemoryStreamTest.txt", FileMode.Open, FileAccess.Read);  
        BinaryReader r = new BinaryReader (fs);  
  
        //以二进制方式读取文件中的内容  
        int i = r.ReadInt32 ();  
        float f = r.ReadSingle ();  
        double d = r.ReadDouble ();  
        bool b = r.ReadBoolean ();  
        string s = r.ReadString();  
        Debug.Log (i);  
        Debug.Log (f);  
        Debug.Log (d);  
        Debug.Log (b);  
        Debug.Log (s);  
  
        r.Close ();  
        fs.Close ();  
    }  
  
  	// 写入文件
    void WriteFile()       
    {  
        FileStream fs = new FileStream ("D:\\BinaryStreamTest.txt", FileMode.OpenOrCreate);  
        BinaryWriter w = new BinaryWriter (fs);  
  
        //以二进制方式向创建的文件中写入内容   
        w.Write (666);                   //  整型  
        w.Write (66.6f);                // 浮点型  
        w.Write (6.66);                // double型  
        w.Write(true);                 // 布尔型  
        w.Write ("六六六");         // 字符串型  
  
        w.Close ();  
        fs.Close();  
    }    
}  

StreamReader与StreamWriter#

StreamReader 或 StreamWriter 通过使用特定编码在字符与字节之间进行转换,提供了高效的流读写功能,可以直接用字符串进行读写,而不用转换成字节数组

文件编码
默认情况下,StreamReaderStreamWriter 类都使用 UTF-8 编码。UTF-8 编码正确处理 Unicode 字符并确保操作系统的本地化版本之间保持一致。

StreamWriter 类构造函数和常用方法如下:

函数 描述
StreamWriter(Stream stream) 构造函数,StreamWriter不仅能对FileStream对象,而且能够对NetWorkStream、MemoryStream等继承了Stream类的流对象进行封装;
StreamWriter(string path) 构造函数,如需要处理的是文件流,则可直接利用文件路径创建以UTF8编码的StreamWriter对象;
StreamWriter(string path, Encoding encoding) 构造函数,同上,可以指明编码格式
Write(string value) 向数据流写入数据;
WriteLine(string value) 向数据流写入数据,并追加一个换行符(Unix)或回车换行符(Windows);
Close() 关闭流,释放资源;
StreamReader 类构造函数和常用方法如下:
函数 描述
StreamReader(Stream stream) 构造函数,利用流对象创建StreamReader对象;
StreamReader(string path) 构造函数,如需要处理的是文件流,则可直接利用文件路径创建以UTF8编码的StreamReader对象;
StreamReader(string path, Encoding encoding) 构造函数,同上,可以指明编码格式
string ReadLine() 读取数据直到遇到换行符(Unix)或回车换行符(Windows);
string ReadToEnd() 读取到文件尾的全部数据
int Peek() 返回数据中下一个可用字符的编码值,如到达文件末尾则返回-1;
Close() 关闭流,释放资源;
/// 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;
}

/// 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
     { }
} 
posted @   二次元攻城狮  阅读(373)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
  1. 1 烟花易冷 小柔Channel
  2. 2 红颜如霜 江壹纯
  3. 3 不谓侠 小桃Channel
  4. 4 小小恋歌 新坦结衣
  5. 5 神预言 袁娅维TIARAY
小小恋歌 - 新坦结衣
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.
点击右上角即可分享
微信分享提示
主题色彩