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

本文关键字:最简单 方法 是什么 文件 二维数组 | 更新日期: 2023-09-27 18:04:41

用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);

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

参考资料:

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");

使用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);
    }
}

如果您必须保留与旧'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();
            }
        }
    }
}
    // 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]);
        }
    }