怎样用C#语言读取txt文本文件中的数据到数组中,以便之后使用?

文本中具体格式为:
300,0,,,0,,,,,,,335,0,,,,,64
300,1,,,0,,,,,,,335,1,,,,,78
300,2,,,0,,,,,,,335,2,,,,,75
301,3,,,133,,,,,,,335,3,,,,,70
301,4,,,134,,,,,,,336,4,,,,,73
将其读入到数组中,读出后形如a[0]=0,a[3]=133,b[0]=64,b[4]=73,第一列和第四列数字可以不用理,感谢各位大虾们!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
 
namespace ConsoleFileRead
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int[]> list = new List<int[]>();
            using (TextReader reader = File.OpenText("data.txt"))
            {
                string s = reader.ReadLine();
                while (s != null)
                {
                    list.Add(ToIntArray(s));
                    s = reader.ReadLine();
                }
            }
 
            //转换结果
            int[][] result = list.ToArray();
        }
 
        static int[] ToIntArray(string s)
        {
            string[] sdata = s.Split(',');
            int[] data = new int[sdata.Length];
            for (int i = 0; i < sdata.Length; i++)
            {
                if (!string.IsNullOrEmpty(sdata[i]))
                {
                    data[i] = int.Parse(sdata[i]);
                }
            }
            return data;
        }
    }
}

result是一个二维数组,你可以在根据你的需要,对二维数组result进行进一步处理。

附:data.txt
300,0,,,0,,,,,,,335,0,,,,,64
300,1,,,0,,,,,,,335,1,,,,,78
300,2,,,0,,,,,,,335,2,,,,,75
301,3,,,133,,,,,,,335,3,,,,,70
301,4,,,134,,,,,,,336,4,,,,,73

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-02

手写的,没分大小写,自己处理下

string file=@"c:\123.txt";
string[] lines=File.ReadAllLines(file);
foreach(string line in lines)
{
   string[] temp=line.Split(',');
   //第一次循环时,此处的temp[0]即为第一行第一列的300,temp[1]即为0,大约temp[10]就是335(你可以自己数一下)按你自己的需要处理就行了,是放入二维数组还是List<string>之类的就看你需要了。后续行以此类推
}

本回答被网友采纳
第2个回答  2015-08-07
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleFileRead
{
class Program
{
static void Main(string[] args)
{
List<int[]> list = new List<int[]>();
using (TextReader reader = File.OpenText("data.txt"))
{
string s = reader.ReadLine();
while (s != null)
{
list.Add(ToIntArray(s));
s = reader.ReadLine();
}
}

//转换结果
int[][] result = list.ToArray();
}

static int[] ToIntArray(string s)
{
string[] sdata = s.Split(',');
int[] data = new int[sdata.Length];
for (int i = 0; i < sdata.Length; i++)
{
if (!string.IsNullOrEmpty(sdata[i]))
{
data[i] = int.Parse(sdata[i]);
}
}
return data;
}
}
}
相似回答