C#如何控制读取ReadStream流的字节数组的大小和文件本身大小一样
时间: 2023-12-06 09:44:19 浏览: 117
在C#中,可以使用`FileStream`类来读取文件流并控制读取的字节数组大小。以下是一个示例代码:
```csharp
using System.IO;
class Program
{
static void Main(string[] args)
{
string filePath = @"C:\example.txt";
int bufferSize = 1024; // 每次读取的字节数组大小
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
byte[] buffer = new byte[bufferSize];
int bytesRead = 0;
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
// 处理读取到的字节数组
// ...
if (fs.Position == fs.Length)
{
// 文件读取完成
break;
}
}
}
}
}
```
在以上示例中,我们通过指定每次读取的字节数组大小来控制读取的文件流大小,并通过比较当前文件流位置和文件大小来判断文件是否已经读取完成。注意,`FileStream`类也可以用于写入文件流。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)