网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
👉本文关键字:System.IO、Stream类、流、方法示例、C#
文章目录
-
-
- 1️⃣ System.IO命名空间
- 2️⃣ Stream类
-
- ♈ 定义
- ♉ 构造函数
- ♊ 属性
- ♌ 常用方法
-
- Close() 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
- CopyTo(Stream) 从当前流中读取字节并将其写入到另一流中
- CopyTo(Stream, Int32) 使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中
- CopyToAsync(Stream) 从当前流中异步读取字节并将其写入到另一个流中
- Dispose() 释放由 Stream 使用的所有资源
- Read(Byte[], Int32, Int32) 当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数
- ReadAsync(Byte[], Int32, Int32) 从当前流异步读取字节序列,并将流中的位置提升读取的字节数
- Write(Byte[], Int32, Int32) 当在派生类中重写时,向当前流中写入字节序列,并将此流中的当前位置提升写入的字节数
- WriteAsync(Byte[], Int32, Int32) 将字节序列异步写入当前流,并将流的当前位置提升写入的字节数
- Close() 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
- ♍ 注解
- ♎ 更多方法
- ♈ 定义
- 1️⃣ System.IO命名空间
-
1️⃣ System.IO命名空间
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
- FileStream类
文件流类,负责大文件的拷贝,读写。
- Path类
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
- File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
- Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
2️⃣ Stream类
♈ 定义
提供字节序列的一般视图。 这是一个抽象类。
public abstract class Stream : MarshalByRefObject, IAsyncDisposable, IDisposable
♉ 构造函数
初始化 Stream 类的新实例
protected Stream ();
♊ 属性
CanRead 当在派生类中重写时,获取指示当前流是否支持读取的值
public abstract bool CanRead { get; }
示例
using System;
using System.IO;
class TestRW
{
public static void Main(String[] args)
{
FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate, FileAccess.Read);
if (fs.CanRead && fs.CanWrite)
{
Console.WriteLine("MyFile.txt can be both written to and read from.");
}
else if (fs.CanRead)
{
Console.WriteLine("MyFile.txt is not writable.");
}
}
}
CanWrite 当在派生类中重写时,获取指示当前流是否支持写入功能的值
public abstract bool CanWrite { get; }
示例
using System;
using System.IO;
class TestRW
{
public static void Main(String[] args)
{
FileStream fs = new FileStream("MyFile.txt", FileMode.OpenOrCreate,
FileAccess.Write);
if (fs.CanRead && fs.CanWrite) {
Console.WriteLine("MyFile.txt can be both written to and read from.");
}
else if (fs.CanWrite) {
Console.WriteLine("MyFile.txt is writable.");
}
}
}
//This code outputs "MyFile.txt is writable."
//To get the output message "MyFile.txt can be both written to and read from.",
//change the FileAccess parameter to ReadWrite in the FileStream constructor.
Length 当在派生类中重写时,获取流长度(以字节为单位)
public abstract long Length { get; }
♌ 常用方法
Close() 关闭当前流并释放与之关联的所有资源(如套接字和文件句柄)
public virtual void Close ();
注意:此方法调用 Dispose ,指定
true
以释放所有资源。 不需要专门调用 Close 方法。 请确保 Stream 已正确释放每个对象。 可以 Streamusing
Using
在 Visual Basic) 中 (或块中声明对象,以确保释放流及其所有资源,或者可以显式调用 Dispose 方法。
CopyTo(Stream) 从当前流中读取字节并将其写入到另一流中
public void CopyTo (System.IO.Stream destination);
参数
destination
Stream
当前流的内容将复制到的流。
示例
下面的示例将的内容复制 FileStream 到 MemoryStream 中。
// Create the streams.
MemoryStream destination = new MemoryStream();
using (FileStream source = File.Open(@"c:\temp\data.dat",
FileMode.Open))
{
Console.WriteLine("Source length: {0}", source.Length.ToString());
// Copy source to destination.
source.CopyTo(destination);
}
Console.WriteLine("Destination length: {0}", destination.Length.ToString());
CopyTo(Stream, Int32) 使用指定的缓冲区大小,从当前流中读取字节并将其写入到另一流中
public virtual void CopyTo (System.IO.Stream destination, int bufferSize);
参数
destination
Stream
当前流的内容将复制到的流。
bufferSize
Int
缓冲区的大小。 此值必须大于零。 默认大小为 81920。
CopyToAsync(Stream) 从当前流中异步读取字节并将其写入到另一个流中
public System.Threading.Tasks.Task CopyToAsync (System.IO.Stream destination);
参数
destination
Stream
当前流的内容将复制到的流。
示例
下面的示例演示如何使用两个 FileStream 对象将文件从一个目录异步复制到另一个目录。 FileStream 类是从 Stream 类派生的。 请注意, Click 控件的事件处理程序 Button 使用修饰符标记, async
因为它调用异步方法
using System;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
namespace WpfApplication
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
string StartDirectory = @"c:\Users\exampleuser\start";
string EndDirectory = @"c:\Users\exampleuser\end";
foreach (string filename in Directory.EnumerateFiles(StartDirectory))
{
using (FileStream SourceStream = File.Open(filename, FileMode.Open))
{
using (FileStream DestinationStream = File.Create(EndDirectory + filename.Substring(filename.LastIndexOf('\\'))))
{
await SourceStream.CopyToAsync(DestinationStream);
}
}
}
}
}
}
CopyToAsync方法使你可以在不阻塞主线程的情况下执行占用大量资源的 i/o 操作。
Dispose() 释放由 Stream 使用的所有资源
public void Dispose ();
Read(Byte[], Int32, Int32) 当在派生类中重写时,从当前流读取字节序列,并将此流中的位置提升读取的字节数
public abstract int Read (byte[] buffer, int offset, int count);
参数
buffer
Byte[]
字节数组。 当此方法返回时,此缓冲区包含指定的字符数组,此数组中
offset
和 (offset
+count
- 1) 之间的值被从当前源中读取的字节所替换。
offset
buffer
中的从零开始的字节偏移量,从此处开始存储从当前流中读取的数据。
count
要从当前流中最多读取的字节数。
返回
读入缓冲区中的总字节数。 如果很多字节当前不可用,则总字节数可能小于请求的字节数;如果已到达流结尾,则为零 (0)。
示例
下面的示例演示如何使用 Read 读取数据块。
using System;
using System.IO;
public class Block
{
public static void Main()
{
Stream s = new MemoryStream();
for (int i = 0; i < 122; i++)
{
s.WriteByte((byte)i);
}
s.Position = 0;
// Now read s into a byte buffer with a little padding.
byte[] bytes = new byte[s.Length + 10];
int numBytesToRead = (int)s.Length;
int numBytesRead = 0;
do
{
// Read may return anything from 0 to 10.
int n = s.Read(bytes, numBytesRead, 10);
numBytesRead += n;
numBytesToRead -= n;
} while (numBytesToRead > 0);
s.Close();
Console.WriteLine("number of bytes read: {0:d}", numBytesRead);
}
}
使用 CanRead 属性确定当前实例是否支持读取。 使用 ReadAsync 方法从当前流异步读取。
此方法的实现从当前流中读取最大字节
count
数,并存储从buffer
开始的字节offset
。 流中的当前位置按读取的字节数进行高级;但是,如果发生异常,则流中的当前位置保持不变。 实现返回读取的字节数。 在没有任何数据可用时,实现将一直阻止,直到至少可以读取一个字节的数据。 Read 仅在流中没有更多数据且预期没有更多数据(例如关闭套接字或文件结尾) (返回 0) 。 即使尚未到达流的末尾,实现也能够返回比请求的更少的字节。
ReadAsync(Byte[], Int32, Int32) 从当前流异步读取字节序列,并将流中的位置提升读取的字节数
public System.Threading.Tasks.Task<int> ReadAsync (byte[] buffer, int offset, int count);
参数
buffer
Byte[]
要写入数据的缓冲区。
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
eading.Tasks.Task ReadAsync (byte[] buffer, int offset, int count);
**参数**
>
> `buffer`
>
>
> [Byte](https://bbs.csdn.net/topics/618545628)[]
>
>
> 要写入数据的缓冲区。
[外链图片转存中...(img-Z0YGgp5Q-1715798194047)]
[外链图片转存中...(img-z15tQJEz-1715798194047)]
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**