在C中,将`StreamReader`转换为二进制数据可以通过以下步骤实现:
一、将文本文件转换为二进制数据
通过`FileStream`以二进制模式读取文本文件,避免使用`StreamReader`的文本解码步骤,直接获取字节数组。
```csharp
string filePath = "yourfile.txt";
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, fileBytes.Length);
// fileBytes 现在包含文件的二进制数据
}
```
使用`MemoryStream`进行中间转换
若需在内存中处理数据,可先读取到`MemoryStream`,再根据需要写入其他流。
```csharp
string filePath = "yourfile.txt";
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (MemoryStream ms = new MemoryStream())
{
fs.CopyTo(ms);
byte[] fileBytes = ms.ToArray();
// fileBytes 包含二进制数据
}
```
二、注意事项
编码问题: 若文本文件使用特定编码(如GB2312),建议在读取时显式指定编码,避免解码错误。 资源管理
三、示例:完整流程
以下是一个将文本文件转换为二进制数据并保存到新文件的完整示例:
```csharp
string inputFilePath = "input.txt";
string outputFilePath = "output.bin";
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
using (FileStream fsOutput = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte;
int bytesRead;
while ((bytesRead = fsInput.Read(buffer, 0, buffer.Length)) > 0)
{
fsOutput.Write(buffer, 0, bytesRead);
}
}
```
此示例通过分块读取和写入,适用于处理大文件。