简体   繁体   English

使用 C# 将 CSV 文件读入数组

[英]Read a CSV file in to an array using C#

I am trying to write code that will pull in, read, and separate a csv file.我正在尝试编写将拉入、读取和分离 csv 文件的代码。 It has four columns with no titles.它有四列,没有标题。 I've been searching for hours online and no one really seems to have the answer so I'm hoping that someone here can.我已经在网上搜索了几个小时,但似乎没有人真正知道答案,所以我希望这里有人可以。 After it is read in I need it to be able to be pulled very specifically as it is part of design.读入后,我需要它能够非常具体地拉出,因为它是设计的一部分。 Thanks ahead of time!提前致谢!

Your question is a little vague, but I'll try and answer it as best I can.你的问题有点含糊,但我会尽力回答。

A CSV file is (by definition) a file containing comma seperated values - the key here is that a comma is used as the delimiter. CSV 文件(根据定义)是一个包含逗号分隔值的文件 - 这里的关键是逗号用作分隔符。 Personally, I find that using a different delimiter is prone to less nasties when parsing.就我个人而言,我发现在解析时使用不同的分隔符容易减少麻烦。

I've created the following test CSV file:我创建了以下测试 CSV 文件:

Column1,Column2,Column3,Column4
Row1Value1,Row1Value2,Row1Value3,Row1Value4
Row2Value1,Row2Value2,Row2Value3,Row2Value4
Row3Value1,Row3Value2,Row3Value3,Row3Value4
Row4Value1,Row4Value2,Row4Value3,Row4Value4
Row5Value1,Row5Value2,Row5Value3,Row5Value4

Here's some code to read that file into some simple structures that you can then manipulate.下面是一些代码,用于将该文件读入一些简单的结构中,然后您可以对其进行操作。 You might want to extend this code by creating classes for the columns and rows (and values as well).您可能希望通过为列和行(以及值)创建类来扩展此代码。

        string sFileContents = "";

        using (StreamReader oStreamReader = new StreamReader(File.OpenRead("Test.csv")))
        {
            sFileContents = oStreamReader.ReadToEnd();
        }

        List<string[]> oCsvList = new List<string[]>();

        string[] sFileLines = sFileContents.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        foreach (string sFileLine in sFileLines)
        {
            oCsvList.Add(sFileLine.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
        }

        int iColumnNumber = 0;
        int iRowNumber = 0;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

        iColumnNumber = 4;
        iRowNumber = 2;

        Console.WriteLine("Column{0}, Row{1} = \"{2}\"", iColumnNumber, iRowNumber, oCsvList[iColumnNumber][iRowNumber]);

Keep in mind that values are accessed by the column number, and then the row number.请记住,值是通过列号访问的,然后是行号。

I hope this helps.我希望这有帮助。

All you need to do is simply convert it into a byte[] array and back into a string[builder?].您需要做的只是将其转换为 byte[] 数组,然后再转换回 string[builder?]。 Then seperate each entry, and parse it like so.然后将每个条目分开,并像这样解析它。

http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Convert-file-to-byte-array.html http://www.digitalcoding.com/Code-Snippets/C-Sharp/C-Code-Snippet-Convert-file-to-byte-array.html

And to convert to a string:并转换为字符串:

    // C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);

You have to understand you need to make a parser.你必须明白你需要做一个解析器。 I made one to pull in Yahoo Stocks, basically splitting the colons into data.我做了一个拉入雅虎股票,基本上将冒号拆分为数据。

This is a much simpler way to do what you want.这是一种更简单的方法来做你想做的事。

var lineCount = File.ReadLines(@"C:\file.txt").Count();
var reader = new StreamReader(File.OpenRead(@"C:\location1.csv"));
int[,] properties = new int[lineCount,4];
for(int i2 = 0; i2 < 4; i2++)
{
    for(int i = 0; i < lineCount; i++)
    {
        var line = reader.ReadLine();
        var values = line.Split(';');
        properties[i,i2] = Convert.ToInt32(values[i2];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM