简体   繁体   English

如何在字符串数组中读取* .csv文件

[英]how read *.csv file in string array

try to realize reading csv file with some structured data (this file used for my programm reminder - data in file structured with next way: date , name, time from, time till, description). 尝试用一些结构化数据来读取csv文件(这个文件用于我的程序提醒 - 用下一个方式构建的文件中的数据:日期,名称,时间,时间,描述)。 Currently i want to read all data from file and put it in some string array, where each element - 1 line from file. 目前我想从文件中读取所有数据并将其放在一些字符串数组中,其中每个元素 - 文件中的1行。 what was done 做了什么

write some code, that create stream for reading and opening file. 编写一些代码,创建用于读取和打开文件的流。 But currently i can only read one line. 但目前我只能阅读一行。 or all file in one line. 或一行中的所有文件。 How to know, how many lines in file exist? 怎么知道,文件中有多少行? or how to read all lines in file in array, where eaach element - one line from file. 或如何读取数组中文件中的所有行,其中eaach元素 - 文件中的一行。

Code

    FileStream fs = new FileStream(FilePath, FileMode.Open,
               FileAccess.Read, FileShare.None);
        StreamReader sr = new StreamReader(fs);

        string lines = sr.ReadLine();
       //temp veiw result
        viewTextBox.Text = lines; //read only one first line in file
        sr.Close();

or try to read all lines 或尝试阅读所有行

        string []line = File.ReadAllLines(FilePath); //read all lines in File
       //temp check
        for (int i=0; i<line.Length;i++){
            viewTextBox.Text += line[i]; // in this case all data stored in one lines
        }

i need this array with data, because next action - search some data in this array and show it in form. 我需要这个数组包含数据,因为下一步操作 - 搜索此数组中的一些数据并以表格形式显示。

Instead of re-inventing the wheel, I'd rather use a well know and tested library: 我宁愿使用一个知名且经过测试的库,而不是重新发明轮子:

"CSV File Parser C# classes for reading and writing CSV files. Support for multi-line fields, custom delimiter and quote characters, options for how empty lines are handled. - Designed to behave much in the way Excel handles CSV files. - Support for multi-line fields. - Ability to customize how empty lines are handled. - Ability to customize delimiter and quote characters." “用于读取和写入CSV文件的CSV文件解析器C#类。支持多行字段,自定义分隔符和引号字符,处理空行的选项。 - 旨在表现出Excel处理CSV文件的方式。 - 支持多行字段。 - 能够自定义空行的处理方式。 - 能够自定义分隔符和引号字符。“

http://csvfile.codeplex.com/ http://csvfile.codeplex.com/

If you just want to see a simple solution to how you could do it: 如果您只是想看看如何做到这一点的简单解决方案:

IEnumerable<string[]> lineFields = File.ReadAllLines(FilePath).Select(line => line.Split(','));

So then you can access columns by index: 那么你可以按索引访问列:

string cellValue = lineFields[lineIndex][columnIndex];

This won't deal with csv files which employ quotes to allow commas within data, for that you'll need to write a routine for splitting quoted strings. 这不会处理使用引号来允许数据中的逗号的csv文件,因为您需要编写用于拆分引用字符串的例程。

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

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