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

标签 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);

但是它不适用于二维数组。

最佳答案

引用资料:

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

关于c# - 将二维数组写入文件的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15512263/

相关文章:

c# - 如何使用 C# 代码运行 C# 代码?

C# IF 部分正常工作,但是,ELSE 部分始终执行

c++ - 在 C++ 中声明数组的最佳方法是什么?

javascript - 如何用图像填充数组?

javascript - 如何检测 js 文件在运行时是否被缩小 (Node.js)

c# - 从线性信息实现 CSV 生成器的方法

c# - 扩展方法和 GetBytes 实现

PHP:如何将数组值插入到mysql语句中

java - Java 中的 "reached end of file while parsing"是什么意思?

C:通过套接字发送和接收文件