各位大虾:
     一个二维数组里有大量数据(几万个元素),怎么以二进制的形式保存到文件中?读取数据时怎么把这些数据读出来并赋值到一维数组,每赋值一次则表示把二维数组里一行的所有读出来了!!可能讲的不是很清楚 
     麻烦各位来看看
谢谢!!

解决方案 »

  1.   


    public static T Copy<T>(this Array array)
    {
               MemoryStream ms = new MemoryStream();
                BinaryFormatter bf = new BinaryFormatter();
                ms.Seek(0, SeekOrigin.Begin);
                bf.Serialize(ms, this);
                ms.Seek(0, SeekOrigin.Begin);
                return (T)bf.Deserialize(ms);
    }序列化和反序列化
      

  2.   

    把二维数组的各维长度先写到文件中,在把所有数据附上就可以了。
    读的时候先读各维长度,在读数据就恢复你的二维数组了。
    // 写
    double[,] d = new double[480, 320];
    // ...
    byte[] bytes = new byte[sizeof(int)*2 + Buffer.ByteLength(d)];
    BitConverter.GetBytes(d.GetLength(0)).CopyTo(bytes, 0);
    BitConverter.GetBytes(d.GetLength(1)).CopyTo(bytes, sizeof(int));
    Buffer.BlockCopy(d, 0, bytes, sizeof(int) * 2, Buffer.ByteLength(d));
    File.WriteAllBytes("c:\\temp\\a.dat", bytes);// 读
    byte[] raw = File.ReadAllBytes("c:\\temp\\a.dat");
    int y = BitConverter.ToInt32(raw, 0), x = BitConverter.ToInt32(raw, sizeof(int));
    if( y*x*sizeof(double) != raw.Length - sizeof(int)*2 ) throw new Exception("file corrupted");
    double[,] data = new double[y, x];
    Buffer.BlockCopy(raw, sizeof(int) * 2, data, 0, Buffer.ByteLength(data));
      

  3.   


    只要看懂BitConverter和Buffer类就是了,查msdn。还有这个方法假定你的元素是基本类型,如int,byte。不能是对象。