簡體   English   中英

如何使用c#讀取二進制文件?

[英]How to read a binary file using c#?

我有一個二進制文件。 我不知道如何使用C#讀取這個二進制文件。

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

如何在C#中讀取包含這些記錄的二進制文件,並在編輯后將其寫回?

實際上有一種更好的方法是使用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);
        }
    }

請參閱下面的示例。

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

希望有幫助......

您可以使用FileStream來讀取文件 - 使用File.Open方法打開文件並獲取FileStream - 查看此處了解更多詳細信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM