C# - 从已知偏移量的文件中获取字节

C# - Get bytes from file at known offset

预先说明一下,这是我第一个正确的 C# 程序,我的编程经验主要是为 TES5Edit 制作 Pascal 脚本。在 Lazarus 中制作了两个实际程序,但是,呃,它们非常糟糕。

在此处上传我的当前代码:http://www.mediafire.com/download/fadr8bc8d6fv7cf/WindowsFormsApplication1.7z

总之!我目前正在尝试做的是获取 .dds 文件中两个特定偏移量的字节值。 x 分辨率保留在偏移量 +0c 处,由两个字节组成(+0c 和 +0d)。 y分辨率的相同演出; @偏移+10 & +11。我在这里上传了我的发现:http://pastebin.com/isBKwaas

但是,我不知道该怎么做。我能够从各种 google 结果中破译的最多结果是:

        public void GetDDSDimensions(string strDDSFilename, out int iSourceDDSx, out int iSourceDDSy)
    {
        FileStream fsSourceDDS = new FileStream(strDDSFilename, FileMode.Open, FileAccess.Read);
        int iWidthOffset = 12; // 0c in hex, if byte is 00, then size is => 256, so get +0d as well
        int iHeightOffset = 16; // 10 in hex, same gig as above. Get byte @ +11 if +10 is 00.
        byte[] bufferDDSBytes = new byte[24]; // @ Offset +24 , byte is always 01. Use as a wee, err, "landmark".

    }

不知道如何从那里继续前进。我需要以某种方式设置 bufferDDSBytes 以获取 fsSourceDDS 中的前 24 个字节,然后比较十六进制值 @ +0c 和 +10,以获得 .dds 文件的分辨率。

比较应该很容易; C# 应该有一个等同于 Pascal 的 StrToInt() 函数的十六进制,不是吗?

首先,使用 using :-)

using (FileStream fsSourceDDS = new FileStream(strDDSFilename, FileMode.Open, FileAccess.Read))
{
     // do something with the FileStream
} // Ensures that it is properly closed/disposed

要转到流中的特定偏移量,请使用 Seek 方法:

fsSourceDDS.Seek(someOffset, SeekOrigin.Begin);

并在其上调用 ReadByteRead 方法以获得所需的字节数。读取字节后,流中的位置按读取的字节数前进。您可以使用 Position 属性 获取流中的当前位置。要直接从流中读取小端值,可以使用 BinaryReader class.

结合以上所有内容:

using (FileStream fsSourceDDS = new FileStream(strDDSFilename, FileMode.Open, FileAccess.Read))
using (BinaryReader binaryReader = new BinaryReader(fsSourceDDS))
{
    fsSourceDDS.Seek(0x0c, SeekOrigin.Begin);
    ushort with = binaryReader.ReadUInt16();
    fsSourceDDS.Seek(0x10, SeekOrigin.Begin);
    ushort height = binaryReader.ReadUInt16();
}