在本文中,我们将通过如何使用 C# 控制台应用程序将字节转换为流。在此示例中,首先,我们使用 File.ReadAllBytes 方法从文件中读取所有字节。然后使用 MemoryStream 我们将所有字节添加到内存流中。为了逐个读取字节,我们使用 BinaryReader 和 for 循环。使用 C# 将字节转换为内存流或流还有另一种选择。
让我们开始编码。
方法一
从文件中读取所有字节,然后将其转换为 MemoryStream 并再次转换为 BinaryReader 以读取数组的每个字节。
byte[] file = File.ReadAllBytes("{FilePath}");
using (MemoryStream memory = new MemoryStream(file))
{
using (BinaryReader reader = new BinaryReader(memory))
{
for (int i = 0; i < file.Length; i++)
{
byte result = reader.ReadByte();
Console.WriteLine(result);
}
}
}
方法二
从文件中读取所有字节并将其转换为 Stream:
byte[] file = File.ReadAllBytes("{FilePath}");
Stream stream = new MemoryStream(file);