C#读文件中数据到数组,并输出数组中存放的数据

我这段代码有问题啊,到底在哪出问题了,代码中30是我瞎写的,要读完整个文件中的数据存入数组,是不是有length之类的函数可以计算长度?麻烦高手解决,很急啊,谢谢解答
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader objReader = new StreamReader("d:\\C#.txt");
string sLine = "";
ArrayList arrText = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
string[] array = arrText.Split(',');

objReader.Close();
for (int i = 0; i < 30; i++)
{
Console.WriteLine(array[i]);
}
}
}
}
鉴于帮助我的人的建议,代码修改如下,还是不对,望有人能运行一下代码,帮助我修改一下,谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader objReader = new StreamReader("d:\\C#.txt");
string sLine = "";
ArrayList arrText = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine();
if (sLine != null)
arrText.Add(sLine);
}
string[] result = System.IO.File.ReadAllText("d:\\C#.txt").Split(',');

objReader.Close();
for (int i = 0; i < result.Length; i++)
{
Console.WriteLine(result[i]);
}
}
}
}

第1个回答  2009-02-10
string[] result=System.IO.File.ReadAllText(文件路径).Split(',');
//数量
result.Length;

//按照你的要求
string content = System.IO.File.ReadAllText(@"C:\C#.txt");
string[] contentArray = content.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

//放的列表
List<int[]> list = new List<int[]>();

for (int i = 0; i < contentArray.Length; i+=3)
{
int a, b, c;
//判断一下,防止上标出界
if (i + 2 <= contentArray.Length)
{
//防止数据异常
if (!int.TryParse(contentArray[i], out a) || !int.TryParse(contentArray[i + 1], out b) || !int.TryParse(contentArray[i + 2], out c))
{
int[] res = new int[3];
res[0] = a;
res[1] = b;
res[2] = c;

list.Add(res);
}
}
}

//list即为所需本回答被提问者采纳
第2个回答  2009-02-10
ArrayList是一个OBJECT的列表清单,与数组的作用类似,你把每行的字符串添加到arrText,要访问ArrayList中的数据要通过arrText[从0开始的数字]来访问,你那样访问是错的。arrText.Split(',')不能这样用
第3个回答  2016-01-04
使用for循环语句+文件操作函数即可文件中数据读取并存到数组中。
1、C语言标准库提供了一系列文件操作函数。文件操作函数一般以f+单词的形式来命名(f是file的简写),其声明位于stdio.h头文件当中。例如:fopen、fclose函数用于文件打开与关闭;fscanf、fgets函数用于文件读取;fprintf、fputs函数用于文件写入;ftell、fseek函数用于文件操作位置的获取与设置。一般的C语言教程都有文件操作一章,可以找本教材进一步学习。
2、例程:

#include<stdio.h>
int i,a[100];
int main(){
FILE * fp1 = fopen("input.txt", "r");//打开输入文件
FILE * fp2 = fopen("output.txt", "w");//打开输出文件
if (fp1==NULL || fp2==NULL) {//若打开文件失败则退出
puts("不能打开文件!");
rturn 0;
}
for(i=0;fscanf(fp1,"%d",a+i)!=EOF;i++);//从输入文件连续读取整数到数组a
for(;i--;)fscanf(fp2,"%d ",a[i]);//把数组a逆序写入到输出文件当中
fclose(fp1);//关闭输入文件
fclose(fp2);//关闭输出文件,相当于保存
return 0;
}
相似回答