c# 读取文件内容存放到int数组 array.txt
程序员文章站
2024-03-11 20:31:43
复制代码 代码如下:using system; using system.data; using system.configuration; using system.we...
复制代码 代码如下:
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.collections;
using system.io;
using system.text;
/// <summary>
/// summary description for readfile
/// </summary>
public class readfile
{
public readfile()
{
//
// todo: add constructor logic here
//
}
public int[,] readfiletoarray()
{
int[,] iret = null;
arraylist alnumline = getfilecontent();
string[] strlinearr = null;
if (alnumline.count > 0)
{
strlinearr = convert.tostring(alnumline[0]).trim(',').split(',');
iret = new int[alnumline.count, strlinearr.length];
for (int i = 0; i < alnumline.count; i++)
{
strlinearr = convert.tostring(alnumline[i]).trim(',').split(',');
for (int j = 0; j < strlinearr.length; j++)
{
iret[i, j] = convert.toint32(strlinearr[j]);
}
}
}
return iret;
}
public arraylist getfilecontent()
{
arraylist alret = new arraylist();
string strfilepath = httpcontext.current.server.mappath("~") + "/array.txt";
if (!file.exists(strfilepath))
{
httpcontext.current.response.write("文件[" + strfilepath + "]不存在。");
return alret;
}
try
{
//读出一行文本,并临时存放在arraylist中
streamreader sr = new streamreader(strfilepath, encoding.getencoding("gb2312"));
string l;
while ((l = sr.readline()) != null)
{
if (!string.isnullorempty(l.trim()))
alret.add(l.trim());
}
sr.close();
}
catch (ioexception ex)
{
httpcontext.current.response.write("读文件出错!请检查文件是否正确。");
httpcontext.current.response.write(ex.tostring());
}
return alret;
}
}