简体   繁体   中英

C# - Get bytes from file at known offset

As a wee fore-note, this is me first proper C# program, and me experience with programming is mostly with making Pascal scripts for TES5Edit. Made two actual programs in Lazarus but, err, they're pretty terrible.

Uploaded me current code 'ere: http://www.mediafire.com/download/fadr8bc8d6fv7cf/WindowsFormsApplication1.7z

Anyhow! What I'm currently trying to do, is get the byte values at two specific offsets in a .dds file. The x resolution is kept @ offset +0c, and consists of two bytes (so +0c and +0d). Same gig for the y resolution; @ offset +10 & +11. I uploaded me findings here: http://pastebin.com/isBKwaas

I've no clue how to do this, however. The most I've been able to decipher from various google results, has resulted with this:

        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".

    }

No clue how to move on from there. I need to somehow set bufferDDSBytes to nab the first 24 bytes in fsSourceDDS, then compare the hex values @ +0c and +10, in order to get the resolution of the .dds file.

Comparing should be easy; C# should have a hex equivalent to Pascal's StrToInt() function, no?

first, use using :-)

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

To go to a specific offset in the stream, use the Seek method:

fsSourceDDS.Seek(someOffset, SeekOrigin.Begin);

and call ReadByte or Read method on it to get as many bytes as you want. After reading bytes, the position in the stream is advanced by the number of bytes read. You can get the current position in the stream with the Position property. To read little-endian values directly from the stream, you can use the BinaryReader class.

To combine all of the above:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM