我正在尝试读取包含多行内容的CSV文件。
这就是CSV的样子:
第1行,列'详情'有多行。
当我尝试使用ReadLine()
方法阅读时:
private void buttonBrowse_Click(object sender, EventArgs e)
{
openFileDialog.Filter = "Excel Worksheets|*.csv";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
String filePathAndName = openFileDialog.FileName;
StreamReader reader = new StreamReader(filePathAndName);
String line = reader.ReadLine();
Console.WriteLine(line);
do
{
line = reader.ReadLine();
Console.WriteLine(line);
} while (line != null);
}
}
它将具有多行的单元格拆分为行数:
[1]"Time of Day","Process Name","PID","Operation","Path","Result","Detail","Image Path"
[2]"22:52:24.2905182","notepad.exe","4828","Process Start","","SUCCESS","Parent PID: 2484, Command line: ""C:\Windows\system32\notepad.exe"" , Current directory: C:\Users\User\, Environment:
[3]; =::=::\
[4]; ALLUSERSPROFILE=C:\ProgramData
[5]; APPDATA=C:\Users\User\AppData\Roaming
[6]; asl.log=Destination=file
[7]; CommonProgramFiles=C:\Program Files\Common Files
...
"22:52:24.2905201","notepad.exe","4828","Thread Create","","SUCCESS","Thread ID: 8008","C:\Windows\system32\notepad.exe"
"22:52:24.2915842","notepad.exe","4828","Load Image","C:\Windows\System32\notepad.exe","SUCCESS","Image Base: 0x6f0000, Image Size: 0x30000","C:\Windows\system32\notepad.exe"
在上面的日志中,第2-7行应该是一行。
我想像PowerShell一样使用import-csv
函数很好地阅读它:
您可以使用命令(示例)轻松地通过行和列从特定单元格中提取数据:
$csvContent[0] |select -expand Detail
例:
答案 0 :(得分:4)
您可以使用像CsvHelper这样的库,而不是手动读取行,这将解除解析csv带来的许多麻烦。
答案 1 :(得分:1)
我知道这不是一个很好的方法,但它适用于我的情况:
lineCounter = 0;
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
if(values.Length == 1)
{
list4[lineCounter-1] += values[0];
}
else
{
list1.Add(values[0]);
list2.Add(values[1]);
list3.Add(values[2]);
list4.Add(values[3]);
lineCounter++;
}
}
答案 2 :(得分:0)