首页 > 解决方案 > C# 读取 DWORD 块中的文件

问题描述

我正在尝试将二进制文件读入字节数组。

我需要以 DWORD 块(或 4 个字节)读取文件,并将每个块存储到字节数组的单个元素中。这是我迄今为止所取得的成就。

using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    var block = new byte[4];
    while (true)
    {
       byte[] temp = new byte[4];
       fs.Read(temp, 0, 4);
       uint read = (byte)BitConverter.ToUInt32(temp, 0);
       block[0] = read???
    }
}

但是,将uint readat 转换为元素block[0]不起作用。我似乎找不到一种不会产生错误的方法。

感谢您的输入。

标签: c#arraysfilestreamdword

解决方案


// read all bytes from file
var bytes = File.ReadAllBytes("data.dat");

// create an array of dwords by using 4 bytes in the file
var dwords = Enumerable.Range(0, bytes.Length / 4)
                       .Select(index => BitConverter.ToUInt32(bytes, index * 4))
                       .ToArray();

// down-casting to bytes
var dwordsAsBytes = dwords.Select(dw => (byte)dw).ToArray();

推荐阅读