将二维数组写入文件的最简单方法是什么?

时间:2013-03-19 23:10:31

标签: c# arrays file

在C#中将二维数组写入文件的最简单方法是什么?

到目前为止我读到的所有问题都是字符串数组,但我需要写数据。 我正在转换一个旧的C项目,它很容易在C:

FILE *file;
unsigned char site[32][10];

初始化数组并打开文件进行读/写(文件始终在项目中打开):

写数据:

if (fseek (file, offset, SEEK_SET))
  return (0);
return (fwrite (&site, sizeof (site), 1, file));

阅读数据:

if (fseek (file, offset, SEEK_SET))
  return (0);
return (fread (&site, sizeof (site), 1, fsite));

该文件不必一直打开,所以我尝试了:

byte [,] = new byte[32,10] = { some data here };
File.WriteAllBytes(fileDescr, site);

然而,它不适用于二维数组。

4 个答案:

答案 0 :(得分:4)

<强>参考文献:

using System.Runtime.Serialization.Formatters.Binary;

<强>方法:

public static void Serialize(object t, string path)
{
    using(Stream stream = File.Open(path, FileMode.Create))
    {
        BinaryFormatter bformatter = new BinaryFormatter();
        bformatter.Serialize(stream, t);
    }
}
//Could explicitly return 2d array, 
//or be casted from an object to be more dynamic
public static object Deserialize(string path) 
{
    using(Stream stream = File.Open(path, FileMode.Open))
    {
        BinaryFormatter bformatter = new BinaryFormatter();
        return bformatter.Deserialize(stream);
    }
}

正在使用

//Saving
byte[,] TestArray = new int[1000,1000];
//...Fill array
Serialize(TestArray, "Test.osl");

//Loading
byte[,] TestArray = (byte[,])Deserialize("Test.osl");

答案 1 :(得分:1)

如果必须保持与旧“C”程序文件格式的向后兼容性,则最简单的方法是使用Windows API来编写数据。 (如果没有,您应该使用前面答案中提到的BinaryFormatter)。

但如果你想要使用Windows API,这是一个例子:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;

namespace Demo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var site = new byte[32,10];

            using (var fs = new FileStream("C:\\TEST\\TEST.BIN", FileMode.Create))
            {
                FastWrite(fs, site, 0, 32*10);
            }
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]

        private static extern bool WriteFile
        (
            IntPtr hFile,
            IntPtr lpBuffer,
            uint nNumberOfBytesToWrite,
            out uint lpNumberOfBytesWritten,
            IntPtr lpOverlapped
        );

        public static void FastWrite<T>(FileStream fs, T[,] array, int offset, int count) where T : struct
        {
            int sizeOfT = Marshal.SizeOf(typeof (T));
            GCHandle gcHandle = GCHandle.Alloc(array, GCHandleType.Pinned);

            try
            {
                uint bytesWritten;
                uint bytesToWrite = (uint) (count*sizeOfT);

                if (!WriteFile(
                    fs.SafeFileHandle.DangerousGetHandle(),
                    new IntPtr(gcHandle.AddrOfPinnedObject().ToInt64() + (offset*sizeOfT)),
                    bytesToWrite,
                    out bytesWritten,
                    IntPtr.Zero
                )){
                    throw new IOException("Unable to write file.", new Win32Exception(Marshal.GetLastWin32Error()));
                }

                Debug.Assert(bytesWritten == bytesToWrite);
            }

            finally
            {
                gcHandle.Free();
            }
        }
    }
}

答案 2 :(得分:0)

使用System.Runtime.Serialization.Formatters.Binary.BinaryFormatter

public void Serialize(String path, byte[,] myArray)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
    {
        formatter.Serialize(stream, myArray);
    }
}

要读取文件,请使用BinaryFormatter的Deserialize方法。

public byte[,] Deserialize(String path)
{
    BinaryFormatter formatter = new BinaryFormatter();
    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        byte[,] myArray = (byte[,])formatter.Deserialize(stream);
    }
}

答案 3 :(得分:0)

    // For I/O
    using System.IO;  

    // Output Stream Writer variable
    StreamWriter yourOSW;  

    // Open the file
    yourOSW = new StreamWriter(fileName); 

    // To declare array
    byte[,] yourArray = new byte[numRows, numColumns];  

    // Data value
    byte num = 0;  

    // To fill array (example)
    for(byte i = 0; i < numRows; i++)
    {
        for(byte j = 0; j < numColumns; j++)
        {
            yourArray[i,j] = num;
            num++;
        }
    }

    // To write array to file
    for(byte i = 0; i < numRows; i++)
    {
        for(byte j = 0; j < numColumns; j++)
        {
            yourOSW.WriteLine(yourArray[i,j]);
        }
    }