簡體   English   中英

從二進制文件讀取可變大小的字符串(VB6與C#)

[英]Read variable sized string from binary file (VB6 vs. C#)

我有一個包含以下內容的二進制文件:

替代文字

以下代碼用於在舊的VB6程序中讀取此內容:

Private Type tpClient
    Firstname As String
    LastName As String
    Birth As String
    Adres As String
    Geslacht As String
    IDNummer As Long
    SSNummer As String
    DatabaseID As Long
    Telefoon1 As String
    Telefoon2 As String
End Type

Open strFilePath For Random Access Read As #intFileNumber
Get #intFileNumber, 1, ClientData ' ClientData is of type tpClient

現在,我嘗試使用新的C#程序閱讀此內容:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PatientStruct
{
    [MarshalAs(UnmanagedType.BStr)]
    public string FirstName;

    [MarshalAs(UnmanagedType.BStr)]
    public string LastName;

    [MarshalAs(UnmanagedType.BStr)]
    public string BirthDate;

    [MarshalAs(UnmanagedType.BStr)]
    public string Address;

    [MarshalAs(UnmanagedType.BStr)]
    public string Gender;

    [MarshalAs(UnmanagedType.BStr)]
    public string IdNumber;

    [MarshalAs(UnmanagedType.BStr)]
    public string SsNumber;

    [MarshalAs(UnmanagedType.BStr)]
    public string DatabaseId;

    [MarshalAs(UnmanagedType.BStr)]
    public string Telephone1;

    [MarshalAs(UnmanagedType.BStr)]
    public string Telephone2;
}

byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, (int)stream.Length);
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T stuff = (PatientStruct)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();

但是,我在調用Marshal.PtrToStructure時收到AccessViolationException。

有什么建議么?

Marshal.PtrToStructure期望buffer充滿指向字符串的指針。 我認為Marshal不能用來做你想做的事。

相反,您需要確定二進制文件格式,並為此手工編寫代碼。 看一下BinaryReader類。

編輯:如果遇到問題,可以添加對Microsoft.VisualBasic.dll的引用,並使用FileSystem.FileGetObject方法。 此行為與VB6中的Get關鍵字相同。

首先,您的結構根本不應該是結構,而應該是一個類。 結構旨在用於表示單個值的小型不變類型。

完全按照您的需要編組數據類型確實很棘手,而且由於您沒有進行互操作,所以您實際上根本不需要編組數據。 僅使用BinaryReader從文件讀取數據會更容易。

可以直接讀取簡單的數據類型,並可以像這樣讀取字符串:

string value = reader.ReadChars(reader.ReadShort());

打開閱讀器時,請指定適當的單字節編碼,例如Windows-1252。

暫無
暫無

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

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