简体   繁体   English

如何使用c#读取二进制文件?

[英]How to read a binary file using 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: C ++中描述的二进制文件中记录的定义是:

#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........
}

How do I read a binary file containing those records in C# and write it back after editing it? 如何在C#中读取包含这些记录的二进制文件,并在编辑后将其写回?

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): 实际上有一种更好的方法是使用struct类型和StructLayout直接映射到二进制文件中的数据结构(我没有测试过实际的映射,但这是一个查找并检查你得到的内容的问题从阅读文件回来):

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

See the sample below. 请参阅下面的示例。

 public byte[] ReadByteArrayFromFile(string fileName)
{
  byte[] buff = null;
  FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  BinaryReader br = new BinaryReader(fs);
  long numBytes = new FileInfo(fileName).Length;
  buff = br.ReadBytes((int)numBytes);
  return buff;
}

Hope that helps... 希望有帮助......

您可以使用FileStream来读取文件 - 使用File.Open方法打开文件并获取FileStream - 查看此处了解更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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