我有一个.csv文件,在不同的框(行和列)中有不同的文本,但我试图将它们放在我的应用程序中。我可以从文件中抓取,但我似乎无法使第1行是列表,第2行是不同的列表等等。我想知道你是否可以提供帮助。
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = filePath;
openFileDialog1.Filter = "Comma Seperated Vaule File (*.csv)|*.csv";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Title = "Find Text File";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
System.IO.Stream fileStream = openFileDialog1.OpenFile();
string filePath = @"C:\Users\16muellerm\Desktop\examplecsv.csv";
StreamReader sr = new StreamReader(filePath);
var lines = new List<string[]>();
string[] Line = sr.ReadLine().Split(',');
//string[] completedLine = new List<string[]>();
int Row = 0;
while (!sr.EndOfStream)
{
lines.Add(Line);
Row++;
//Console.WriteLine(Row);
for (int i = 1; i <= Line.Count() ; i++)
{
richTextBox1.Text += Line[i-1];
}
}
var data = lines.ToArray();
/* using (myStream )
{
textBox1.Text = openFileDialog1.InitialDirectory;
var reader = new System.IO.StreamReader(fileStream);
// Insert code to read the stream here.
// for (int i = 1; i <= 5; i++)
var lines = reader.ReadToEnd();
richTextBox1.Text = lines;
for (int i = 1; i <= lines.Count()-1; i++) {
var line = lines[i];
list.Add(lines[i].ToString());
list.ForEach(updateStuff);
}
}*/
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
感谢您的回复。
答案 0 :(得分:3)
这是一个选择吗?
File.ReadAllLines( fileName ).Select( x => x.Split( seperator ) ).ToList()
你会得到一个行列表,每行有一个字符串数组。