【发布时间】:2014-12-25 16:30:47
【问题描述】:
我有一个 CSV 文件,我需要在 C# 中将其作为顺序文件打开。它必须由标头解析。
到目前为止,我只知道如何使用 C# System.IO 库将数据文件作为顺序文件加载到 ArrayList 结构中。文件中的每一行都必须是单独的记录。就是这里:
using System;
using System.IO;
using System.Collections;
namespace FileSearch
{
class Class1
{
static void Main(string[] args)
{
StreamReader objReader = new StreamReader("c:\\Users/Sarah/Desktop/IP4Data.csv"); //open file to read
string sLine = ""; //string variable for data that goes into ArrayList
ArrayList arrText = new ArrayList();
while (sLine != null)
{
sLine = objReader.ReadLine(); //read file one line at a time
if (sLine != null) //if empty, it's null
arrText.Add(sLine);//Add data to Array List
}
objReader.Close(); //end loop
foreach (string sOutput in arrText) //Outputs read data from ArrayList onto screen
Console.WriteLine(sOutput);
Console.ReadLine();
}
}
}
如何解析 CSV 文件,以便可以在 ArrayList 中搜索它?
【问题讨论】:
-
你读过 CSV 文件是如何构建的吗?如果是,你明白了吗?如果是,您是否已开始实施?
-
您有什么理由使用
ArrayList而不是List<>?不是说无效,it's just the old way of doing it. -
您需要提供 CSV 样本并描述您的意思
searchable -
对于
String.Split()无法处理的更复杂的解析,我尝试使用Regex.Split()和this Java solution 中的模式",(?=([^\"]*\"[^\"]*\")*[^\"]*$)",但它没有提供正确的结果。也许您或其他人可以修复它以在 C# 中工作。