C#如何 struct 存入文件同c入格式
我在c中有一 struct { char name[32],
DWORD age;
}user;
在置好 struct 的料後
以 WriteFile(hFile, (LPBYTE)&user,sizeof(user), &retlen, NULL); 入文件
今我要以c#去做和上面一的事
要怎撰才能生一格式的文件呢
我以序列化方式入
但入的料都不同
有好的方式可以解?
[Serializable]
internal struct User
{
internal string name;
internal int age;
}
User user;
user.name = tmpName.PadRight(32, ' ');
user.age = tmpAge;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
bf.Serialize(stream, user);
byte[] buff = stream.ToArray();
FileStream fs = new FileStream(writeFileName, FileMode.Create);
fs.Write(buff, 0, buff.Length);
fs.Close();
[解决办法]
引入命名空间:
using System;
using System.Runtime.InteropServices;
/// <summary>
/// 结构体转换成字节数组
/// </summary>
/// <param name="structure">结构体</param>
/// <returns>字节数组</returns>
public static Byte[] StructToBytes(Object structure) {
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);
Byte[] bytes = new Byte[size];
Marshal.StructureToPtr(structure, buffer, false);
Marshal.Copy(buffer, bytes, 0, size);
Marshal.FreeHGlobal(buffer);
return bytes;
}
/// <summary>
/// 字节数组转换成结构体
/// </summary>
/// <param name="bytes">字节数组</param>
/// <param name="strcutType">结构体类型</param>
/// <returns>结构体</returns>
public static Object BytesToStruct(Byte[] bytes, Type strcutType) {
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, buffer, size);
Object obj = Marshal.PtrToStructure(buffer, strcutType);
Marshal.FreeHGlobal(buffer);
return obj;
}
[解决办法]
- C# code
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] private byte[] name; [MarshalAs(UnmanagedType.I4)] private int age;
[解决办法]
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct User {
/// char[32]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
public char[] name;
/// DWORD->unsigned int
public uint age;
}