将.csv文件解析为二维数组 [英] Parsing .csv file into 2d array

查看:309
本文介绍了将.csv文件解析为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将CS​​V文件解析为C#中的2D数组.我遇到一个非常奇怪的问题,这是我的代码:

I'm trying to parse a CSV file into a 2D array in C#. I'm having a very strange issue, here is my code:

string filePath = @"C:\Users\Matt\Desktop\Eve Spread Sheet\Auto-Manufacture.csv";
StreamReader sr = new StreamReader(filePath);
data = null; 
int Row = 0;
while (!sr.EndOfStream)
{
    string[] Line = sr.ReadLine().Split(',');
    if (Row == 0)
    {
        data = new string[Line.Length, Line.Length];
    }
    for (int column = 0; column < Line.Length; column++)
    {
        data[Row, column] = Line[column];
    }
    Row++;
    Console.WriteLine(Row);
}

我的.csv文件有87行,但是在执行过程中存在一个奇怪的问题,它将完全按预期方式将前15行读入数据数组,但是当它第16次下降到data[Row, column] = Line[column];行时它似乎只是打破了整个循环(不满足sr.EndOfStream条件),并且没有将更多数据读入数据数组.

My .csv file has 87 rows, but there is a strange issue in the execution where it will read the first 15 rows into the data array exactly as expected but when it gets down to the data[Row, column] = Line[column]; line for the 16th time it seems to just break out of the entire loop (without meeting the sr.EndOfStream condition) and not read any more data into the data array.

任何人都可以解释发生了什么事吗?

Can anyone explain what might be happening?

推荐答案

您的代码中没有任何内容可以及时使用文件中的行数.

Nothing in your code gets the number of lines out of your file in time to use it.

Line.Length表示csv中的列数,但是您似乎也在尝试使用它来指定文件中的行数.

Line.Length represents the number of columns in your csv, but it looks like you're also trying to use it to specify the number of lines in your file.

这应该为您带来预期的结果:

This should get you your expected result:

string filePath = @"C:\Users\Matt\Desktop\Eve Spread Sheet\Auto-Manufacture.csv";
StreamReader sr = new StreamReader(filePath);
var lines = new List<string[]>();
int Row = 0;
while (!sr.EndOfStream)
{
    string[] Line = sr.ReadLine().Split(',');
    lines.Add(Line);
    Row++;
    Console.WriteLine(Row);
}

var data = lines.ToArray();

这篇关于将.csv文件解析为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆