0Pricing
C# Academy · 课时

简单的 CSV 解析模式

解析 CSV 行:对简单文件使用朴素的 Split,对数字使用安全的 TryParse,然后编写一个能处理引号内逗号的小型分割器。

简单的 CSV 解析模式 是 CoddyKit 上的免费 C# Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。

CSV 解析概览

目的:可靠地解析小型 CSV。

  • 对于不含引号的文件,先使用简单的 Split
  • 使用 TryParse 解析数字
  • 使用小型扫描器处理带引号的字段

简单拆分(不含引号)

对于不含引号的 CSV,简单的 Split 即可正常工作,而且易于阅读。

using System;

public class Program
{
  public static void Main(string[] args)
  {
    // Simple: no quotes, commas separate fields
    string line = "Apple,10,2.5";
    string[] parts = line.Split(','); // naive split

    Console.WriteLine("Name = " + parts[0]);
    Console.WriteLine("Qty  = " + parts[1]);
    Console.WriteLine("Price= " + parts[2]);
  }
}

安全解析数字

使用 Trim,并结合区域性信息使用 TryParse(例如 InvariantCulture),以避免错误数据导致程序崩溃。

using System;
using System.Globalization;

public class Program
{
  public static void Main(string[] args)
  {
    string line = "Banana, 7, 1.99";
    string[] p = line.Split(',');

    string name = p[0].Trim();
    int qty;
    double price;

    bool okQty = Int32.TryParse(p[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
    bool okPrice = Double.TryParse(p[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);

    Console.WriteLine("Parsed: " + name + " | ok=" + (okQty && okPrice) + " -> " + qty + " x " + price);
  }
}

简单拆分为何会失败

带引号的字段可能包含逗号;普通的 Split 会将一个字段拆成多个部分。

using System;

public class Program
{
  public static void Main(string[] args)
  {
    // Name has a comma inside quotes; naive split breaks it
    string line = "\"Orange, Blood\",12,3.40";
    string[] parts = line.Split(','); // wrong: splits inside the quoted name

    Console.WriteLine("Parts found = " + parts.Length); // 4, not 3
    foreach (string s in parts) Console.WriteLine("[" + s + "]");
  }
}

识别引号的拆分

小型扫描器会切换 inQuotes 状态,并忽略引号内的逗号;它还会处理成对的引号("")。

using System;
using System.Collections.Generic;
using System.Text;

public class Program
{
  // Splits a CSV line handling quotes and doubled "" inside quoted fields.
  static List<string> SplitCsvLine(string line)
  {
    List<string> fields = new List<string>();
    StringBuilder sb = new StringBuilder();
    bool inQuotes = false;

    for (int i = 0; i < line.Length; i++)
    {
      char c = line[i];

      if (c == '\"')
      {
        if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
        {
          // Escaped quote ("") inside a quoted field
          sb.Append('\"');
          i++; // skip next quote
        }
        else
        {
          inQuotes = !inQuotes; // toggle
        }
      }
      else if (c == ',' && !inQuotes)
      {
        fields.Add(sb.ToString());
        sb.Length = 0; // reset
      }
      else
      {
        sb.Append(c);
      }
    }

    fields.Add(sb.ToString());
    return fields;
  }

  public static void Main(string[] args)
  {
    string line = "\"Orange, Blood\",12,\"He said \"\"Hi!\"\"\"";
    List<string> parts = SplitCsvLine(line);

    Console.WriteLine("Fields = " + parts.Count);
    foreach (string f in parts) Console.WriteLine("[" + f + "]");
  }
}

从 CSV 转换为对象

将拆分器与 TryParse 及最少量的清理操作结合起来,即可安全地构建类型明确的对象。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

public sealed class Product
{
  public string Name;
  public int Quantity;
  public double Price;
}

public class Program
{
  static List<string> SplitCsvLine(string line)
  {
    List<string> fields = new List<string>();
    StringBuilder sb = new StringBuilder();
    bool inQuotes = false;

    for (int i = 0; i < line.Length; i++)
    {
      char c = line[i];
      if (c == '\"')
      {
        if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
        { sb.Append('\"'); i++; }
        else { inQuotes = !inQuotes; }
      }
      else if (c == ',' && !inQuotes)
      { fields.Add(sb.ToString()); sb.Length = 0; }
      else
      { sb.Append(c); }
    }
    fields.Add(sb.ToString());
    return fields;
  }

  static bool TryParseProduct(string line, out Product p)
  {
    p = null;
    List<string> f = SplitCsvLine(line);
    if (f.Count < 3) return false;

    string name = f[0].Trim().Trim('\"');
    int qty;
    double price;

    bool okQty = Int32.TryParse(f[1].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out qty);
    bool okPrice = Double.TryParse(f[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out price);
    if (!okQty || !okPrice) return false;

    p = new Product { Name = name, Quantity = qty, Price = price };
    return true;
  }

  public static void Main(string[] args)
  {
    string[] lines = new string[]
    {
      "\"Orange, Blood\",12,3.4",
      "Apple,10,2.5",
      "\"He said \"\"Hi\"\"\",1,0.0"
    };

    List<Product> list = new List<Product>();
    foreach (string line in lines)
    {
      Product p;
      if (TryParseProduct(line, out p)) list.Add(p);
    }

    foreach (Product p in list)
    {
      Console.WriteLine(p.Name + " -> " + p.Quantity + " @ " + p.Price);
    }
  }
}

带引号字段的规则

快速检查:如何正确处理带引号的 CSV 字段中的逗号?

回顾

回顾:不含引号的 CSV 使用简单的 Split,数字使用 TryParse 解析;当字段可能包含逗号时,改用识别引号的扫描器。

常见问题解答

「简单的 CSV 解析模式」课时是免费的吗?

是的 — 「简单的 CSV 解析模式」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。

「简单的 CSV 解析模式」这节课中我会学到什么?

解析 CSV 行:对简单文件使用朴素的 Split,对数字使用安全的 TryParse,然后编写一个能处理引号内逗号的小型分割器。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 C# Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「简单的 CSV 解析模式」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 C# Academy 课中编写并运行代码吗?

能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. System.IO(路径与流)
  2. 使用 System.Text.Json 处理 JSON(选择加入与转换器)
  3. 简单的 CSV 解析模式
← 返回 C# Academy