【发布时间】:2014-12-15 11:32:55
【问题描述】:
我写了一个小程序从csv文件中读取数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace test
{
class Program
{
static void Main( string[] args )
{
var reader = new StreamReader( File.OpenRead( @"C:\Users\Desktop\Results.csv" ) );
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while ( !reader.EndOfStream )
{
var line = reader.ReadLine();
var values = line.Split( ',' );
listA.Add( values[0] );
listB.Add( values[1] );
}
// Print column one.
Console.WriteLine( "Column 1:" );
foreach ( var element in listA )
Console.WriteLine( element );
// Print column two.
Console.WriteLine( "Column 2:" );
foreach ( var element in listB )
Console.WriteLine( element );
Console.ReadKey();
}
}
}
我在listB.Add( values[1] ); 线上收到以下错误消息
Index was outside the bounds of the array.
当我注释掉与 listB 相关的所有内容时,它会起作用并显示第一列...
有人可以帮我理解我做错了什么吗?
谢谢,
【问题讨论】:
-
values的值是多少?它是否被任何东西填充?它应该填充的字符串是什么? -
在调试器中单步调试代码,您很可能会很快找到问题。
-
没有双关语,当有非常好的库可用时,为什么每个人都尝试编写自己的 CSV 解析器(例如 joshclose.github.io/CsvHelper)?
-
优秀的sn-p,非常感谢:)
标签: c# .net csv console-application