我需要将多维数组保存到文件中。然后可以更改其中的内容,使其也将显示在该文件中,并从该文件加载到数组中。
假设我有一些数组:
private string[,] array = new string[5, 5];
然后,我需要执行一个函数,如果文件不存在,则将用空间填充数组,如果存在,则将其加载。像这样的东西:
private void Load()
{
if (File.Exists("save.txt"))
{
}
else
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
array[i,j] = " ";
}
}
}
}
我检查了文件是否存在,如果不存在,我将用空格填充数组,但是我需要以某种方式以这种格式在文件中写入数组:
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
" ", " ", " "," ", " ",
or in some format, that will work.
然后,我基本上计划用','分割字符串并将其保存到该数组。如果文件存在,则将其读取并将值保存到所述数组。
因此,基本上我需要检查文件是否存在,如果答案为是,则将其加载到多维数组,如果答案为否,则用空字符串填充数组并将其加载到文件中。
如果有人愿意帮助我,我将非常感激。
private string[,] array = new string[5, 5];
public void Load()
{
if (File.Exists("save.txt"))
{
using (StreamReader sr = new StreamReader("save.txt"))
{
string file = sr.ReadToEnd();
string[] fileArr = file.Split(',');
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
array[i, j] = fileArr[i + j];
}
}
}
}
else
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
array[i,j] = " ";
}
}
using (StreamWriter sw = new StreamWriter("save.txt"))
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
sw.Write("{0},", array[i, j]);
}
sw.WriteLine();
}
}
}
}
好,所以我尝试了这个。我的想法是,当我需要更改文件时,我将始终调用Load(),但它会这样返回。image
这是我的写功能:
private void Write()
{
for (int i = 0; i < array.GetLength(1); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
Console.Write("[{0}]", array[j, i]);
}
Console.WriteLine();
}
}