用 C# 读取二进制文件 相关讨论

来源:互联网 发布:面试淘宝美工提问 编辑:程序博客网 时间:2024/04/28 10:49
参考:http://www.chinauml.net/developer/DoNet/20040318/231723.html
//此函数可以容许你把任何对象转换为一系列字节,并可以重新转换回对象
public static byte[] RawSerialize( object anything )
{
       int rawsize = Marshal.SizeOf( anything );
       IntPtr buffer = Marshal.AllocHGlobal( rawsize );
       Marshal.StructureToPtr( anything, buffer, false );
       byte[] rawdatas = new byte[ rawsize ];
       Marshal.Copy( buffer, rawdatas, 0, rawsize );
       Marshal.FreeHGlobal( buffer );
       return rawdatas;
}public static object RawDeserialize( byte[] rawdatas, Type anytype )
{
       int rawsize = Marshal.SizeOf( anytype );
       if( rawsize > rawdatas.Length )
              return null;
       IntPtr buffer = Marshal.AllocHGlobal( rawsize );
       Marshal.Copy( rawdatas, 0, buffer, rawsize );
       object retobj = Marshal.PtrToStructure( buffer, anytype );
       Marshal.FreeHGlobal( buffer );
       return retobj;
}

//自动解决数据中每一段的字节排列顺序问题

public static object EndianFlip(object oObject)
{
       string sFieldType;

       Type tyObject = oObject.GetType();

       FieldInfo[] miMembers;
       miMembers = tyObject.GetFields();

       for (int Looper = miMembers.GetLowerBound(0);
              Looper <= miMembers.GetUpperBound(0);
              Looper++)
       {
              sFieldType = miMembers[Looper].FieldType.FullName;
              if ((String.Compare(sFieldType, "System.UInt16", true) == 0))
              {
                     ushort tmpUShort;
                     tmpUShort = (ushort) miMembers[Looper].GetValue(oObject);
                     tmpUShort = (ushort) (((tmpUShort & 0x00ff) << 8) +
                           ((tmpUShort & 0xff00) >> 8));
                     miMembers[Looper].SetValue(oObject, tmpUShort);
              }
              else
              if (String.Compare(sFieldType, "System.UInt32", true) == 0)
              {
                     uint   tmpInt;
                     tmpInt = (uint) miMembers[Looper].GetValue(oObject);
                     tmpInt = (uint) (((tmpInt & 0x000000ff) << 24) +
                                       ((tmpInt & 0x0000ff00) << 8) +
                                       ((tmpInt & 0x00ff0000) >> 8) +
                                       ((tmpInt & 0xff000000) >> 24));
                     miMembers[Looper].SetValue(oObject, tmpInt);
              }
       }
return (oObject);
}