1

在 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

4 回答 4

5

参考:

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");
于 2013-03-19T23:21:41.207 回答
1

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

但如果你确实想使用 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();
            }
        }
    }
}
于 2013-03-19T23:50:38.683 回答
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);
    }
}
于 2013-03-19T23:34:59.027 回答
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]);
        }
    }
于 2013-03-19T23:43:46.107 回答