如何使用C#读取二进制文件? [英] How to read a binary file using c#?

查看:119
本文介绍了如何使用C#读取二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制文件。我不知道如何使用C#来读取这个二进制文件

I have got a binary file. I have no clue how to read this binary file using C#.

在C ++中描述的的二进制文件中的记录定义是:

The definition of the records in the binary file as described in C++ is:

#define SIZEOF_FILE(10*1024)
//Size of 1234.dat file is: 10480 + 32 byte (32 = size of file header)
typedef struct FileRecord
{
 WCHAR ID[56]; 
 WCHAR Name[56];
 int Gender;
 float Height;
 WCHAR Telephne[56];
 and........
}



我如何读取包含在C#中的那些记录的二进制文件和编辑后写回?

How do I read a binary file containing those records in C# and write it back after editing it?

推荐答案

有实际上是这样做的更好的方式使用结构键入和 StructLayout 直接映射到二进制文件中的数据结构(我没有测试的实际映射,但它是寻找它并检查您读取该文件得到什么)的问题:

There's actually a nicer way of doing this using a struct type and StructLayout which directly maps to the structure of the data in the binary file (I haven't tested the actual mappings, but it's a matter of looking it up and checking what you get back from reading the file):

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]
public struct FileRecord
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
    public char[] ID;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 56)]
    public char[] Name;
    public int Gender;
    public float height;
    //...
}

class Program
{
    protected static T ReadStruct<T>(Stream stream)
    {
        byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
        stream.Read(buffer, 0, Marshal.SizeOf(typeof(T)));
        GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
        T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
        handle.Free();
        return typedStruct;
    }

    static void Main(string[] args)
    {
        using (Stream stream = new FileStream(@"test.bin", FileMode.Open, FileAccess.Read))
        {
            FileRecord fileRecord = ReadStruct<FileRecord>(stream);
        }
    }

这篇关于如何使用C#读取二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆