C# CSV 文件读取的三种方式分析

1 、文件流 + 字符串分割(","),缺点:数据中如果有",",会出现分割错误。

复制代码
public DataTable readCsvSql(string filepath)
{
    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"));
    //记录每次读取的一行记录
    string strLine = null;
    //记录每行记录中的各字段内容
    string[] arrayLine = null;
    //分隔符
    string[] separators = { ",","\t"};
    //逐行读取CSV文件
    while ((strLine = sr.ReadLine()) != null)
    {
         //去除头尾空格
          strLine = strLine.Trim();
          //分隔字符串,返回数组
          arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);

          // arrayLine  就是需要的数据
    }
}

2、 读取数据库表方式

缺点:不同系统上的 Provider 值不一样,没法大面积使用 (Provider=Microsoft.Jet.OLEDB.4.0; 这个在win7上可行,网上说win11有问题)

复制代码
 public DataTable readCsvSql(string filepath)
        {
            DataTable dt = new DataTable();
            try
            {
                string directory = Path.GetDirectoryName(filepath);
                string file = Path.GetFileName(filepath);

                if (file.Trim().ToUpper().EndsWith("CSV"))//判断所要读取的扩展名
                {
                    string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + directory + ";Extended Properties='text;HDR=NO;FMT=Delimited'";//有列的读取
                    string commandText = "select * from [" + file + "]";//SQL语句
                    OleDbConnection olconn = new OleDbConnection(connStr);
                    olconn.Open();
                    OleDbDataAdapter odp = new OleDbDataAdapter(commandText, olconn);
                    odp.Fill(dt);
                    olconn.Close();
                    odp.Dispose();
                    olconn.Dispose();
                }
                else
                {
                    //  异常处理
                }
            }
            catch (Exception ex)
            {
                //  异常处理
            }

            return dt;
        }
  1. 使用 FileIO.TextFieldParser读取, 我现在就采用这个方法,暂时没发现问题 。

    复制代码
         private void ReadCSVFile(string strCsvFilePath)
         {
             using (Microsoft.VisualBasic.FileIO.TextFieldParser csvReader = new Microsoft.VisualBasic.FileIO.TextFieldParser(strCsvFilePath, Encoding.GetEncoding("gb2312")))
             {
                 csvReader.SetDelimiters(new string[] { "," });
                 csvReader.HasFieldsEnclosedInQuotes = true;
                  跳过标题行(如果有)
                 //csvReader.ReadLine();
    
                 while (!csvReader.EndOfData)
                 {
                     string[] arrayLine = csvReader.ReadFields();                
                     // arrayLine 中就是每行的数据
    
                 }  
             }
         }
相关推荐
火兮明兮7 分钟前
Python训练第三十天
开发语言·python
啊我不会诶10 分钟前
CF每日4题(1300-1400)
开发语言·c++·算法
学编程的小白狼24 分钟前
C#:多线程
开发语言·c#
island131424 分钟前
JAVA Web 期末速成
java·开发语言·前端
珊瑚里的鱼29 分钟前
【滑动窗口】LeetCode 1004题解 | 最大连续1的个数 Ⅲ
开发语言·c++·笔记·算法·leetcode
使者大牙30 分钟前
【C语言基础语法入门】通过简单实例快速掌握C语言核心概念
c语言·开发语言
2401_895610821 小时前
Java 后端基础 Maven
java·开发语言·maven
LAM LAB1 小时前
【VBA/word】批量替换字体大小
开发语言·c#·word
zzc9211 小时前
怎么用Origin画出MATLAB效果的3D时频图
开发语言·matlab
小峰编程1 小时前
Python函数——万字详解
linux·运维·服务器·开发语言·前端·网络·python