将`Stream`转换为二进制流通常涉及将流中的数据读取到字节数组中。以下是具体步骤和示例代码:
一、将`Stream`转换为字节数组
使用`FileStream`读取数据 通过`FileStream`的`Read`方法将流中的数据读取到预先分配的字节数组中。需要先获取流的长度,然后创建对应大小的字节数组,最后执行读取操作。
```csharp
using System;
using System.IO;
public static byte[] ConvertStreamToByteArray(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
// 获取流长度
long length = stream.Length;
if (length < 0)
throw new ArgumentException("Stream length cannot be negative.");
// 创建字节数组
byte[] buffer = new byte[(int)length];
// 读取数据到字节数组
stream.Read(buffer, 0, (int)length);
return buffer;
}
```
示例使用:
```csharp
using (FileStream fileStream = new FileStream("input.txt", FileMode.Open, FileAccess.Read))
{
byte[] data = ConvertStreamToByteArray(fileStream);
// 现在data数组包含文件内容
}
```
二、将二进制数据写入新文件
若需将字节数组保存为文件,可使用`FileStream`的`Write`方法:
```csharp
public static void SaveByteArrayToFile(byte[] data, string filePath)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (string.IsNullOrEmpty(filePath))
throw new ArgumentException("File path cannot be null or empty.");
using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
fileStream.Write(data, 0, data.Length);
}
}
```
示例使用:
```csharp
byte[] fileData = Convert.Frombase64String("your_base64_string");
string outputPath = "output.bin";
SaveByteArrayToFile(fileData, outputPath);
```
三、注意事项
异常处理:
实际应用中应添加异常处理机制,例如使用`try-catch`块捕获`IOException`等异常。
大文件处理:
对于大文件,建议使用缓冲区逐块读取(如每次读取4KB),避免一次性分配大内存。
流类型限制:
上述方法适用于`FileStream`,若使用其他类型的流(如`MemoryStream`),需调整读取方式。
通过上述方法,可灵活实现`Stream`与二进制数据之间的转换。