C#中流的使用和分类

 更新时间:2022年07月31日 15:08:03   作者:Darren Ji  
这篇文章介绍了C#中流的使用和分类,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

使用流读取、写入文件

使用流把文件读取到字节数组:

//FileMode.Create, FileMode.Append 
//FileAccess.Write, FileAccess.ReadWrite 
//FileMode和FileAccess搭配使用,如果第二个参数FileMode.Appden写追加,第三个参数FileAccess.Read只读,会抛异常 
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read) 
byte[] buffer = new byte[source.Length]; 
int bytesRead = source.Read(buffer, i, (int)source.Length);

Int32类型的最大值,以及Byte, KB, MB, GB转换:

Int32.MaxValue = 2147483647 Byte 
2147483647/1024 = 2097152 KB(1 KB = 1024 Byte) 
2097152/1024 = 2048 MB(1 M = 1024 KB) 
2048/1024 = 2 G(1G = 1024M)

使用流把字节数组写到文件:

Stream target = new FileStream(@"2.jpg", FileMode.Create, FileAccess.Write);
 
Stream source = new FileStream(@"1.jpg",FileMode.Open, FileAccess.Read) 
byte[] buffer = new byte[source.Length]; 
int bytesRead = source.Read(buffer, i, (int)source.Length);
 
target.Write(buffer, 0, buffer.Length); 
source.Dispose(); 
target.Dispose();

使用流对大文件进行分批读取和写入:

int BufferSize = 10240; // 10KB 
Stream source = new FileStream(@"D:\a.mp3", FileMode.Open, FileAccess.Read); 
Stream target = new FileStream(@"D:\b.mp3", FileMode.Create, FileAccess.Write);
 
byte[] buffer = new byte[BufferSize]; 
int byteRead; 
do{ 
    byteRead = source.Read(buffer, 0, BufferSize); 
    target.Write(buffer, 0, bytesRead); 
} while(byteRead > 0); 
target.Dispose(); 
source.Dispose();

流的分类

在Stream抽象类下包含:
→FileStream→IsolatedStoreageFileStream
→MemoryStream
→NetworkStream

基础流

从流中读取数据:

CanRead()
Read(byte[] buffer, int offset, int count)

向流中写入数据:

CanWrite()
Write(byte[] buffer, int offset, int count)
WriteByte(Byte value)

移动流指针:

CanSeek()
Seek(long offset, SeekOrigion)
Position流的指针位置
Close()
Dispose()
Flush()将缓存设备写入存储设备
CanTimeout()
ReadTimeout()
WriteTimeout()
Length
SetLength(long value)

装饰器流

实现了Decorator模式,包含对Stream抽象基类的引用,同时继承自Stream抽象基类。

  • System.IO.Compression下的DeflateStream和GZipStream用于压缩和解压缩
  • System.Security.Cryptography下的CryptoStream用于加密和解密
  • System.Net.Security下的AuthenticatedStream用于安全性
  • System.IO下的BufferedStream用户缓存

包装器类

不是流类型,而是协助开发者处理流包含的数据,并且不需要将流读取到Byte[]字节数组中。但流的包装器类包含了对流的引用。

StreamReader

继承自TextReader。
将流中的数据读取为字符。

FileStream fs = new FileStream("a.txt", FileMode.Open, FileAcess.Read); 
StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
 
//或者 
//StreamReader reader = new StreamReader("a.txt"); //默认采用UTF-8编码方式

StreamWriter

继承自TextWriter。
将字符写入到流中。

string text = 
@"aa 
bb 
cc";
 
StringReader reader = new StringReader(text); 
int c = reader.Read(); 
Console.Write((char)c);
 
char[] buffer = new char[8]; 
reader.Read(buffer, 0, buffer.Length); 
Console.Write(String.Join("",buffer));
 
string line = reader.ReadLine(); 
Console.WriteLine(line);
 
string rest = reader.ReadToEnd(); 
Console.Write(); 
reader.Dispose();

StringReader和StringWriter

也继承自TextReader和TextWriter,但是用来处理字符串。

BinaryWriter和BinaryReader

BinaryWriter用于向流中以二进制方式写入基元类型,比如int, float, char, string等.BinaryReader用于从流中读取基元类型。注意,这2个类并不是继承TextReader和TextWriter。

namespace ConsoleApplication29 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Product p = new Product("product.bin") 
            { 
                Id = 1, 
                Name = "GOOD", 
                Price = 500F 
            }; 
            p.Save();
 
            Product newP = new Product("product.bin"); 
            newP.Load(); 
            Console.WriteLine(newP); 
            Console.ReadKey(); 
        } 
    }
 
    public class Product 
    { 
        public int Id { get; set; } 
        public string Name { get; set; } 
        public double Price { get; set; }
 
        private string filePath;
 
        public Product(string filePath) 
        { 
            this.filePath = filePath; 
        }
 
        public void Save() 
        { 
            FileStream fs = new FileStream(this.filePath, FileMode.Create,FileAccess.Write); 
            BinaryWriter writer = new BinaryWriter(fs); 
            writer.Write(this.Id); 
            writer.Write(this.Name); 
            writer.Write(this.Price); 
            writer.Dispose(); 
        }
 
        public void Load() 
        { 
            FileStream fs = new FileStream(this.filePath, FileMode.Open,FileAccess.Read); 
            BinaryReader reader = new BinaryReader(fs); 
            this.Id = reader.ReadInt32(); 
            this.Name = reader.ReadString(); 
            this.Price = reader.ReadDouble(); 
            reader.Dispose(); 
        }
 
        public override string ToString() 
        { 
            return String.Format("Id:{0},Name:{1},Price:{2}", this.Id, this.Name, this.Price); 
        } 
    } 
}

结果:

编码方式:
定义了字节如何转换成人类可读的字符或者文本,可以看作是字节和字符的对应关系表。在读取文件采用的编码方式要和创建文件采用的编码方式保持一致。

帮助类

在System.IO命名空间下。

  • File

FileStream fs = File.Create("a.txt");
Open(string path, FileMode mode)
OpenRead()
OpenWrite()
ReadAllText()
ReadAllByte()
WriteBllBytes()
WriteAllLines()
Copy(string sourceFileName, string destFileName)

  • FileInfo
  • Path
  • Directory
  • DirectoryInfo

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

  • C#开发Winform程序调用存储过程

    C#开发Winform程序调用存储过程

    这篇文章介绍了C#开发Winform程序调用存储过程的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-05-05
  • C#中字符串合并的多种实现方法

    C#中字符串合并的多种实现方法

    字符串合并是将两个或多个字符串组合成一个单一字符串的过程,在项目开发中非常常见,C#也为我们提供非常多字符串合并方式,下面一起盘点下,感兴趣的小伙伴跟着小编一起来看看吧
    2025-01-01
  • c#生成高清缩略图的二个示例分享

    c#生成高清缩略图的二个示例分享

    这篇文章主要介绍了c#生成高清缩略图的二个示例,需要的朋友可以参考下
    2014-04-04
  • C#保存listbox中数据到文本文件的方法

    C#保存listbox中数据到文本文件的方法

    这篇文章主要介绍了C#保存listbox中数据到文本文件的方法,涉及C#操作listbox数据的相关技巧,需要的朋友可以参考下
    2015-04-04
  • 关于C#中async/await的用法实例详解

    关于C#中async/await的用法实例详解

    这篇文章主要介绍了关于C#中async/await的用法,今天写一个demo彻底搞明白async/await的用法,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-02-02
  • Unity的IPostprocessBuild实用案例深入解析

    Unity的IPostprocessBuild实用案例深入解析

    这篇文章主要为大家介绍了Unity的IPostprocessBuild实用案例深入解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-05-05
  • Silverlight文件上传下载实现方法(下载保存)

    Silverlight文件上传下载实现方法(下载保存)

    这篇文章主要介绍了Silverlight文件上传下载实现方法(下载保存) ,需要的朋友可以参考下
    2015-11-11
  • C#语言使用gRPC、protobuf(Google Protocol Buffers)实现文件传输功能

    C#语言使用gRPC、protobuf(Google Protocol Buffers)实现文件传输功能

    这篇文章主要介绍了C#语言使用gRPC、protobuf(Google Protocol Buffers)实现文件传输功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-10-10
  • C#基础 延迟加载介绍与实例

    C#基础 延迟加载介绍与实例

    C#基础 延迟加载介绍与实例,有效使用它可以大大提高系统性能,需要的朋友可以参考一下
    2013-04-04
  • C#如何从byte[]中直接读取Structure实例详解

    C#如何从byte[]中直接读取Structure实例详解

    这篇文章主要给大家介绍了关于利用C#如何从byte[]里直接读取Structure的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-03-03

最新评论