解释 .NET 中的流体系结构
.NET 流体系结构提供了一个一致的编程接口,用于跨不同 I/O 类型进行读写操作。它包括用于操作磁盘上的文件和目录的类,以及用于压缩、命名管道和内存映射文件的专用流。
.NET 中的流体系结构依赖于后端存储和适配器。
后端存储
它表示数据存储,例如文件或网络连接。它可以充当可以顺序读取字节的源,也可以充当可以顺序写入字节的目标。
.NET 中的 Stream 类将后端存储公开给程序员。它公开了用于读取、写入和定位的方法。顾名思义,流是流动的数据,可以是每次一个字节,也可以是特定大小的块。数据不会像数组一样一次全部驻留在内存中。流使用的内存量很少,而不管原始数据存储的大小如何。
适配器
通常,流处理字节。虽然字节灵活且高效,但应用程序使用更高级别的抽象。诸如 TextReader/TextWriter 或 XMLReader/XMLWriter 之类的适配器包装一个流并提供对更高级别数据结构(如文本字符串和 XML)的访问。
Stream 类
Stream 类定义在 System.IO 命名空间中,并提供字节序列的通用视图。它是一个抽象类,充当所有流的基类。它公开了用于读取、写入和查找操作的方法,以及其他管理功能,例如关闭和刷新。
Stream 类具有以下成员:
属性
CanRead – 如果当前流支持读取,则返回 true。
CanSeek – 如果当前流支持查找(即查询和修改流中的当前位置),则返回 true。
CanTimeout – 如果当前流可以超时,则返回 true。
CanWrite – 如果当前流支持写入,则返回 true。
Length – 返回流的长度(以字节为单位)。
Position – 获取或设置当前流中的位置。
Readtimeout – 获取或设置一个值(以毫秒为单位),该值确定流在超时之前尝试读取的时间长度。
WriteTimeout – 获取或设置一个值(以毫秒为单位),该值确定流在超时之前尝试写入的时间长度。
方法
public abstract int Read (byte[] buffer, int offset, int count)
在派生类中被重写时,从当前流读取字节序列,并根据读取的字节数递增流中的位置。
public abstract void Write (byte[] buffer, int offset, int count)
在派生类中被重写时,将字节序列写入当前流,并根据写入的字节数递增此流中的当前位置。
public abstract long Seek (long offset, System.IO.SeekOrigin origin);
在派生类中被重写时,设置当前流中的位置。
public abstract void Flush ();
在派生类中被重写时,清除此流的所有缓冲区,并导致任何缓冲数据写入基础设备。
示例
这是一个演示 Stream 用法的完整示例。
using System;
using System.IO;
class Program{
static void Main(string[] args){
// Create a file called test.txt in the current directory:
using (Stream str = new FileStream("sample.txt", FileMode.Create)){
Console.WriteLine(str.CanRead); // True
Console.WriteLine(str.CanWrite); // True
Console.WriteLine(str.CanSeek); // True
str.WriteByte(75);
str.WriteByte(76);
byte[] bytes = { 10, 20, 30 };
str.Write(bytes, 0, bytes.Length); // Write block of 5 bytes
Console.WriteLine(str.Length); // 7
Console.WriteLine(str.Position); // 7
str.Position = 0; // Move back to the start
Console.WriteLine(str.ReadByte()); // 101 Console.WriteLine(str.ReadByte()); // 102
// Read from the stream back into the block array:
Console.WriteLine(str.Read(bytes, 0, bytes.Length)); // 5
// Assuming the last Read returned 5, we'll be at
// the end of the file, so Read will now return 0:
Console.WriteLine(str.Read(bytes, 0, bytes.Length)); // 0
}
}
}输出
True True True 5 5 75 76 3 0
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP