有没有办法将CSV文件读入ArrayList,然后在控制台上打印出来?

时间:2016-05-19 18:16:18

标签: c# csv arraylist

我只是在C#练习。我主要习惯Java,但我一直无法弄清楚如何读取.CSV文件,存储它并将其内容打印到控制台中。这就是我到目前为止所拥有的。我做错了什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            String path = "C:\\Desktop\\csvTestFilePractice\\";
            String file1 = "testFile1.csv";
            ArrayList arryList1 = new ArrayList();
            String[] dataArray1;

            TextFieldParser CSVFile1 = new TextFieldParser(path + file1);
            CSVFile1.SetDelimiters(",");
            dataArray1 = CSVFile1.ReadFields();

            int count = 0;
            while (!CSVFile1.EndOfData)
            {
                dataArray1 = CSVFile1.ReadFields();
                Console.WriteLine(dataArray1);
            }
            Console.Read();
        }
    }
}

这也是我正在测试的文件。

______ Excel查看

ID  Name    Phone          State
1   Colt    864-367-8399    SC
2   Terry   864-367-8400    GA
3   Joe     864-367-8401    FL
4   Mark    864-367-8402    NC
5   Ashley  864-367-8403    CO

____记事本视图

ID,Name,Phone,State
1,Colt,864-367-8399,SC
2,Terry,864-367-8400,GA
3,Joe,864-367-8401,FL
4,Mark,864-367-8402,NC
5,Ashley,864-367-8403,CO

感谢您的任何建议

2 个答案:

答案 0 :(得分:2)

你不应该使用ArrayList,因为它是非泛型集合类型。您应该考虑如何将CSV解析为List以避免必须对您的对象进行装箱/取消装箱。

答案 1 :(得分:1)

根据评论中的问题,这是程序的简短版本,它使用每列的最大长度来创建格式字符串。它应该适用于几乎任何csv文件。我确信它可以改进。所有列都是左对齐的。

void Main()
{
    List<string[]> lines = new List<string[]>();

    TextFieldParser CSVFile1 = new TextFieldParser(@"g:\test\test.csv");
    CSVFile1.SetDelimiters(",");

    //Loop through the data and create a list.  Each entry in the list
    //is a string array.  This method may be impractical for very large 
    //files.
    while (!CSVFile1.EndOfData)
    {
        lines.Add(CSVFile1.ReadFields());
    }

    //Create a format string using the length of the longest string in each column
    string formatString = createFormatString(lines);

    //Loop through all the lines and write them to the console.
    foreach (var csvLine in lines)
    {
        Console.WriteLine(formatString, csvLine);
    }
}

//Create a format string based on the number of columns and the maximum
// size of each column
private string createFormatString(List<string[]> lines)
{
    var sb = new StringBuilder();

    //Use the first array to get the number of columns.  They should all be the same
    int numberOfColumns = lines[0].Length;

    //Loop through the number of columns and find the max length and append to the format string
    for (int i = 0; i < numberOfColumns; i++)
    {
        int maxColumnWidth = lines.Select(l => l[i].Length).Max();
        sb.AppendFormat("{{{0}, -{1}}}  ", i, maxColumnWidth);
    }

    return sb.ToString();
}