2012-06-23 28 views

回答

2

使用CSV解析器 - 有很多.NET,甚至是在VisualBasic命名空间中内置的一个。

请参阅TextFieldParser - 尽管在VisualBasic名称空间中,它是一个常规的.NET库,可供任何.NET语言使用。

还有manyotheroptions

+0

这会分隔每列,并将每列的每个值放入不同的数组? –

+1

@AdamAndre - 它_could_。虽然我通常会创建一个类型来存放数据,并使用该类型的通用集合来将数据存储在有意义且强类型的容器中。 – Oded

+0

好的,谢谢你的帮助! –

0

如果你想要做手工,(我也建议使用TextFieldParser),你可以使用一个StreamReader循环所有线路,并使用String.Split你分离(假设逗号)分割:

var stateList = new List<String>(); 
var countyList = new List<String>(); 
var zipCodeList = new List<String>(); 
var latitudeList = new List<String>(); 
var longitudeList = new List<String>(); 

using (var reader = new System.IO.StreamReader(@"C:\Temp\csv.txt")) 
{ 
    string line; 
    while ((line = r.ReadLine()) != null) 
    { 
     var fields = line.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
     stateList.Add(fields[0]); 
     if (fields.Length > 1) 
      countyList.Add(fields[1]); 
     if (fields.Length > 2) 
      zipCodeList.Add(fields[2]); 
     if (fields.Length > 3) 
      latitudeList.Add(fields[3]); 
     if (fields.Length > 4) 
      longitudeList.Add(fields[4]); 
    } 
} 

如果你真的需要一个数组而不是一个列表:

String[] states = stateList.ToArray(); 
String[] counties = countyList.ToArray(); 
String[] zipCodes = zipCodeList.ToArray(); 
String[] latitudes = latitudeList.ToArray(); 
String[] longitudes = longitudeList.ToArray(); 
相关问题