将结构体写入文件除了用序列化方法之外,还有类似于C++中fwrite之类的直接将结构体中数据写入到文件中去的方法吗??
PS:(不是一行行的写,是没有换行的、紧密相连的数据,规定结构体中的每项都是定长的,要读的时候就定长的读)

解决方案 »

  1.   

    struct t
            {
                public int a;
                public char b;
            }        unsafe static void Main(string[] args)
            {
                t objt = new t();
                objt.a = 30;
                objt.b = 'a';
                t* pt;
                pt = &objt;
                byte* pb = (byte*)pt;
                byte[] buf=new byte[sizeof(t)];
                for (int i = 0; i < buf.Length; i++)
                { 
                    buf[i]=(*pb)++;
                }            FileStream fs = File.Open("c:\\a.dat", FileMode.Create);
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
                fs.Close();
                
               Console.Read();
            }
      

  2.   

    [StructLayout(LayoutKind.Sequential)]
    public struct Point {
        public int x;
        public int y;
    }....
    Point p1 = new Point();
    System.IntPtr p = Marshal.AllocHGlobal( Marshal.SizeOf( p1 ) );
    Marshal.StructureToPtr( p1 , p , true );
    byte[] b = new byte[Marshal.SizeOf(p1)];
    for( int i=0 ; i<Marshal.SizeOf( p1 ) ; i++ )
    {
    b[i] = Marshal.ReadByte( b ,i );
    }