c# - 如何将字节 block 读入结构

标签 c# .net struct filestream

我有这个我需要处理的资源文件,它打包了一组文件。

首先,资源文件列出了其中包含的所有文件,以及一些其他数据,例如在这个结构中:

struct FileEntry{
     byte Value1;
     char Filename[12];
     byte Value2;
     byte FileOffset[3];
     float whatever;
}

所以我需要读取这个大小的 block 。

我正在使用 FileStream 的 Read 函数,但如何指定结构的大小? 我用过:

int sizeToRead = Marshal.SizeOf(typeof(Header));

然后将这个值传递给 Read,但是我只能读取一组 byte[],我不知道如何将其转换为指定的值(我确实知道如何获取单字节值......但不是其他人)。

我还需要指定一个不安全的上下文,我不知道它是否正确...

在我看来,在 .NET 中读取字节流比我想象的要难:)

谢谢!

最佳答案

假设这是 C#,我不会将结构创建为 FileEntry 类型。我会用字符串替换 char[20] 并使用 BinaryReader - http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx阅读个别领域。您必须按照写入数据的顺序读取数据。

类似于:

class FileEntry {
     byte Value1;
     char[] Filename;
     byte Value2;
     byte[] FileOffset;
     float whatever;
}

  using (var reader = new BinaryReader(File.OpenRead("path"))) {
     var entry = new FileEntry {
        Value1 = reader.ReadByte(),
        Filename = reader.ReadChars(12) // would replace this with string
        FileOffset = reader.ReadBytes(3),
        whatever = reader.ReadFloat()           
     };
  }

如果你坚持要有一个结构,你应该让你的结构不可变,并为你的每个字段创建一个带有参数的构造函数。

关于c# - 如何将字节 block 读入结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6918545/

相关文章:

c# - EF6 : Renaming namespace using Code First Migrations

c# - 在 C++ 函数之间传递 C# 类

c# - DI 与一次性元素

c# - 为什么在 C# 中使用 global 关键字?

.net - 对于 .NET ToolStripButton,我可以有多行 "Text"属性吗?

c++ - 显示函数的枚举值

c# - 如何在 Xamarin 中查找当前的 UIViewController

c# - .NET 短唯一标识符

c - 我找不到我的代码的问题

c - 结构体入口声明了一个数组类型的字段,但编译器说它是一个指针