C#檔案流寫入結構體
1、定義結構體
namespace WindowsFormsApplication1
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct fsnHead
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public UInt16[] HeadStart;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
public UInt16[] HeadString;
public UInt32 Counter;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public UInt16[] HeadEnd;
}
}
2、在方法裡處理
private void button1_Click(object sender, EventArgs e)
{
string strFile = Application.StartupPath + "\\Data.dat";
FileStream fs = new FileStream(strFile, FileMode.Open, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
fsnHead fsnHeader = new fsnHead();
int headSize = Marshal.SizeOf(typeof(fsnHead));
byte[] tempReader = new byte[headSize];
fs.Seek(0, SeekOrigin.Begin);
fs.Read(tempReader, 0, headSize);
fsnHeader = (fsnHead)BytesToStuct(tempReader, typeof(fsnHead));
}
public static object BytesToStuct(byte[] bytes, Type type)
{
//得到結構體的大小
int size = Marshal.SizeOf(type);
//byte陣列長度小於結構體的大小
if (size > bytes.Length)
{
//返回空
return null;
}
//分配結構體大小的記憶體空間
IntPtr structPtr = Marshal.AllocHGlobal(size);
//將byte陣列拷到分配好的記憶體空間
Marshal.Copy(bytes, 0, structPtr, size);
//將記憶體空間轉換為目標結構體
object obj = Marshal.PtrToStructure(structPtr, type);
//釋放記憶體空間
Marshal.FreeHGlobal(structPtr);
//返回結構體
return obj;
}