日期:2014-05-18 浏览次数:22008 次
private List<Dictionary<string, string>> ConvertFileToDic(string fileName)
{
char delimiter = ',';
CsvReader reader = null;
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
StreamReader sReader = null;
//读取CSV
sReader = new StreamReader(fileName, Encoding.Unicode);
using (reader = new CsvReader(sReader, true, delimiter))
{
reader.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;
//保证是使用正确的分隔符
int fieldCount = 0;
try
{
fieldCount = reader.FieldCount;
}
catch (Exception)
{
sReader = new StreamReader(fileName, Encoding.Unicode);
reader = new CsvReader(sReader, true, delimiter == '\t' ? ',' : '\t');
fieldCount = reader.FieldCount;
}
if (reader.FieldCount <= 1)
{
sReader = new StreamReader(fileName, Encoding.Unicode);
reader = new CsvReader(sReader, true, delimiter == '\t' ? ',' : '\t');
fieldCount = reader.FieldCount;
}
//CSV标题
string[] headers = reader.GetFieldHeaders();
while (reader.ReadNextRecord())
{
Dictionary<string, string> dic = new Dictionary<string, string>();
try
{
for (int i = 0; i < headers.Length; i++)
{
dic[headers[i]] = reader[i];
}
}
catch (Exception)
{
continue;
}
list.Add(dic);
}
}
if (sReader != null)
{
sReader.Close();
sReader.Dispose();
}
return list;
}
sReader = new StreamReader(fileName, Encoding.Unicode);
sReader.ReadLine(); //<--
sReader.ReadLine(); //<--
using (reader = new CsvReader(sReader, true, delimiter))