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 中就是每行的数据
    
                 }  
             }
         }
相关推荐
青岑CTF35 分钟前
攻防世界-Ics-05-胎教版wp
开发语言·安全·web安全·网络安全·php
Li emily37 分钟前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
码云数智-园园1 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#
APIshop1 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库
血小板要健康1 小时前
Java基础常见面试题复习合集1
java·开发语言·经验分享·笔记·面试·学习方法
淼淼7632 小时前
安装jdk1.8
java·开发语言
PfCoder2 小时前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
Legendary_0082 小时前
Type-C 一拖二快充线:突破单口限制的技术逻辑
c语言·开发语言
过期动态2 小时前
Java开发中的@EnableWebMvc注解和WebMvcConfigurer接口
java·开发语言·spring boot·spring·tomcat·maven·idea
csbysj20202 小时前
Web 标准
开发语言