日期:2014-05-18  浏览次数:21853 次

C# 读取CSV文件中的某一行
我现在有一个CSV文件,要把它读取出来,但是这个CSV文件的前面2行是没用的数据,我想把第3行当成标题列来读取,有什么可用的方法
C# code

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;
        }




------解决方案--------------------
既然你知道前两行没用,那就直接访问第三行就行了,要么就读到内存后,删除列表前两项
------解决方案--------------------
C# code

sReader = new StreamReader(fileName, Encoding.Unicode);
sReader.ReadLine();   //<--
sReader.ReadLine();   //<--
using (reader = new CsvReader(sReader, true, delimiter))