日期:2014-05-19  浏览次数:20814 次

C#读写结构文件的问题
我有一个C++的结构文件要读取,在C++中结构如下(只是举例)
struc   aaa
{
    int   age;
    char   name[20];
    float   money;
    byte   sex;
    DWORD   level;
    int   other[10];
    WORD   photo[128*128];
}aaa;
在C++中我用如下方法就可读取
    FILE   *fp;
    fp   =   fopen( "TESTFILE.DAT ",   "rb ");
    fread(&aaa,   sizeof(aaa),   1,   fp);

我是C#新手:在C#下如何读取这个结构文件呢!多谢!

------解决方案--------------------
先读文件到内存,再拷入结构体中,参考代码
int len = Marshal.Sizeof(typeof(MyStruct));
MyStruct o;
byte[] arr = new byte[len];//{};
IntPtr ptr = Marshal.AllocHGlobal(len);
try
{
// 从byte[] 到struct MyStruct
Marshal.Copy(arr, index, ptr, Math.Min(length, arr.Length - index));
o = (MyStruct)Marshal.PtrToStructure(ptr, typeof(MyStruct));


// 从struct MyStruct 到 byte[]
Marshal.StructureToPtr(o, ptr, true); // 使用时要注意fDeleteOld参数
Marshal.Copy(ptr, arr, 0, len);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
return o;

------解决方案--------------------
这是准备的二进制文件

01 64 64 64 00 00 00 00 00 00 00 00 01 00 00 00
02 63 63 63 63 63 63 00 00 00 00 00 02 00 00 00
03 62 62 62 62 62 62 62 62 62 00 00 03 00 00 00


using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ReadBinary
{
class Program
{
//对应的结构
struct Test {
public byte byteField;//1字节
public string strField;//11字节
public Int32 intField;//4字节
}
static void Main(string[] args)
{
//文件流
using (FileStream fs = new FileStream( "../../TextFile1.Dat ", FileMode.Open, FileAccess.Read))
{
//二进制读
BinaryReader br = new BinaryReader(fs);
byte[] byte16 = new byte[16];
while (br.Read(byte16, 0, 16) == 16) {
//填充结构体,要求结构体是完全知道的
//也可以使用不安全代码直接操作指针
//因为结构体也是值类型的,在内存中连续存放
Test test = getTest(byte16);
//显示
Console.WriteLine( "BYTE:{0} String:{1} Int32:{2} ",test.intField,test.strField,test.intField);
}
Console.Read();
}
}

static Test getTest(byte[] byte16) {
Test test = new Test();
test.byteField=byte16[0];
test.strField = Encoding.ASCII.GetString(byte16, 1, 11);
test.intField = BitConverter.ToInt32(byte16, 12);
return test;
}
}
}