Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 读取csv

作者:死亡之神   发布日期:2026-01-04   浏览:49

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "example.csv"; // CSV文件路径

        try
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    // 按逗号分割每一行的数据
                    string[] values = line.Split(',');

                    // 输出每一列的值
                    foreach (string value in values)
                    {
                        Console.WriteLine(value);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("读取CSV文件时出错: " + ex.Message);
        }
    }
}

解释说明:

  1. 导入命名空间using System;using System.IO; 导入了必要的命名空间,以便使用控制台输出和文件操作。
  2. 定义主程序入口static void Main() 是程序的入口点。
  3. 指定CSV文件路径string filePath = "example.csv"; 定义了要读取的CSV文件路径。
  4. 使用 StreamReader 读取文件:通过 StreamReader 类逐行读取CSV文件的内容。
  5. 处理每一行数据:在 while 循环中,每次读取一行,并使用 Split(',') 方法将该行按逗号分割成多个字段。
  6. 输出每个字段:使用 foreach 循环遍历并输出每个字段的值。
  7. 异常处理:使用 try-catch 块捕获并处理可能发生的异常,如文件不存在或读取错误。

上一篇:c#扩展方法

下一篇:c# string 转 int

大家都在看

c# 二进制

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

c#网络编程

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站