Parsing .csv file into 2d array

后端 未结 5 1548
我寻月下人不归
我寻月下人不归 2021-02-08 01:20

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 Spre         


        
5条回答
  •  耶瑟儿~
    2021-02-08 02:26

    Without knowing the contents of your csv file, I would assume that the error is generated by this line:

    if (Row == 0)
    {
        data = new string[Line.Length, Line.Length];
    }
    

    By initialising the total amount of rows to the amount of columns in the first line of the csv, you are assuming that the amount of rows is always equal to the amount of columns.

    As soon as the amount of rows is greater than the total columns of the first line of the csv, you are going to overrun the data array by attempting to access a row that isn't there.

    You can simplify your code by changing your data to be a list to allow for dynamic adding of items:

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

提交回复
热议问题