c#多维数组在txt文件的存取
来源:互联网 发布:java微信发送消息源码 编辑:程序博客网 时间:2024/06/05 02:39
1.存储数组到txt文件(假设数组为short型)
class VALUE { public string[] value1 = new string[8]; public string[,] value2 = new string[8, 4]; } VALUE[,] sVALUE = new VALUE[w, h]; //定义string数组 // Save Goal Bounds保存目标界限 for (int r = 0; r < w; r++) { for (int c = 0; c < h; c++) { for (int dir = 0; dir < 8; dir++) { if (判断分类) { sVALUE[r,c].value1[dir] =INVALID_GOAL_BOUNDS.ToString(); } else { for (int minMaxIndex = 0; minMaxIndex < 4; minMaxIndex++) { sVALUE[r, c].value2[dir, minMaxIndex] = m_goalBoundsMap[r, c].bounds[dir, minMaxIndex].ToString(); } } }//数组存储 }} short sign11 = 0; string sign2 = sign11.ToString(); StreamWriter sw1 = new StreamWriter("H:/svalue2.txt", true); //第一个参数是读取到流的文件名,第二个参数是如果文件不存在,能否创建文件,true为创建新文件,false为不创建 StreamWriter sw2 = new StreamWriter("H:/svalue1.txt", true); //第一个参数是读取到流的文件名,第二个参数是如果文件不存在,能否创建文件,true为创建新文件,false为不创建 for (int r = 0; r < w; r++) { for (int c = 0; c < h; c++) { for (int dir = 0; dir < 8; dir++) { if (sVALUE[r, c].value1[dir] != null) sw2.Write(sVALUE2[r, c].value1[dir]); //如果不是string数组,可使用.Tostring()转换在进行连接 else sw2.Write(sign2); sw2.WriteLine(); } } } sw2.Flush(); sw2.Close(); sw2.Dispose();
2.从txt读取数组
string path_txt1 = "H:/svalue1.txt"; StreamReader sr1 = new StreamReader(path_txt1, true); for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { for (int dir = 0; dir < 8; dir++) { sVALE1[i, j].value1[dir] =sr1.ReadLine();最终数组【r,c】.value【dir】 =short.Parse(sVALE1[r,c].value1[dir]);//这是最后的转化步骤 } } }
存取没有什么技巧,几维数组就几维读入,几维读出就可以了,如果是比较复杂的数组可以看看txt存取结构体,这一块我目前还没有涉猎。
阅读全文