我有一个二进制文件包含以下内容:
I have a binary file with the following contents:
下面code是用来读取旧VB6程序这个内容:
The following code is used to read this contents in old VB6 program:
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#程序读取这样的:
Now I'm trying to read this with my new C# program:
[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。
However, I get an AccessViolationException on the call to Marshal.PtrToStructure.
有什么建议?
推荐答案
首先,你的结构不应该是一个结构的,而是一个类。结构是适用于小型的,一成不变的类型重新present一个值。
First of all, your struct should not be a struct at all, but a class. Structs are intended for small, immutable types that represent a single value.
制作一个数据类型元帅完全按照你想要的是真正棘手,并作为你是不是做互操作,你真的不需要编组的。它更容易只使用一个 BinaryReader在
从文件中读取数据。
Making a data type marshal exactly as you want is really tricky, and as you are not doing interop you really don't need marshalling at all. It's easier to just use a BinaryReader
to read the data from the file.
简单数据类型可以读直断,字符串可以这样写:
The simple data types can be read straight off, and the strings can be read like this:
string value = reader.ReadChars(reader.ReadShort());
指定一个合适的单字节编码打开阅读器时,例如窗口1252。
Specify an appropriate single byte encoding when opening the reader, for example windows-1252.
相关推荐
最新文章