c#

   我想用C#完成二进制文件的读取.数据结构如下怎么能实现.谢谢
字段1   字段2          字段3 字段4       字段5 字段6
车台ID码 GPS方向数据 指令码 车台状态字  发送时间 GPS时间和定位数据
2字节    1字节          1字节 2字节     3字           1 0字节
   

解决方案 »

  1.   


    byte[] buf = {
                     1,0,
                     2,
                     3,  
                     4,0,
                     5,0,0,                         // 3 bytes
                     6,5,4,3,2,  6,5,4,3,2          // 10 bytes
                 };short id = BitConverter.ToInt16(buf, 0);        // 1
    byte gpsDir = buf[2];                           // 2
    byte instruction = buf[3];                      // 3
    short status = BitConverter.ToInt16(buf, 4);    // 4byte[] location = new byte[10];
    Array.Copy(buf, 9, location, 0, 10);
    buf[9] = 0;int sendTime = BitConverter.ToInt32(buf, 6);    // 5
      

  2.   

    参考下msdn// Create default application settings.
            aspectRatio   = 1.3333F;
            lookupDir     = @"C:\AppDirectory";
            autoSaveTime  = 30;
            showStatusBar = false;        if(File.Exists(fileName))
            {
                BinaryReader binReader =
                    new BinaryReader(File.Open(fileName, FileMode.Open));
                try
                {
                    // If the file is not empty,
                    // read the application settings.
                    // Read 4 bytes into a buffer to
                    // determine if the file is empty.
                    byte[] testArray = new byte[3];
                    int count = binReader.Read(testArray, 0, 3);                if (count != 0)
                    {
                        aspectRatio   = binReader.ReadSingle();
                        lookupDir     = binReader.ReadString();
                        autoSaveTime  = binReader.ReadInt32();
                        showStatusBar = binReader.ReadBoolean();
                    }
                }            // If the end of the stream is reached before reading
                // the four data values, ignore the error and use the
                // default settings for the remaining values.
                catch(EndOfStreamException e)
                {
                    Console.WriteLine("{0} caught and ignored. " +
                        "Using default values.", e.GetType().Name);
                }
                finally
                {
                    binReader.Close();
                }
            }// Create a file and store the application settings.
        public void Close()
        {
            using(BinaryWriter binWriter =
                new BinaryWriter(File.Open(fileName, FileMode.Create)))
            {
                binWriter.Write(aspectRatio);
                binWriter.Write(lookupDir);
                binWriter.Write(autoSaveTime);
                binWriter.Write(showStatusBar);
            }
        }