C#文件流写入结构体

来源:互联网 发布:c语言 char负值 编辑:程序博客网 时间:2024/06/06 03:37


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

0 0