You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现读取无表头的制表符分隔文本文件数据

解决方案

要实现**跳过表头、将所有制表符分隔的数据存入单一List<string>**的需求,只需在现有代码基础上添加表头跳过逻辑,并优化数据添加方式:

var sepList = new List<string>();

using (var file = new StreamReader(docPath))
{
    // 直接读取并丢弃表头行
    file.ReadLine();
    
    string line;
    while ((line = file.ReadLine()) != null)
    {
        // 分割当前行的制表符分隔内容,移除空条目
        var segments = line.Split('\t', StringSplitOptions.RemoveEmptyEntries);
        // 批量添加分割结果,替代循环Add更高效
        sepList.AddRange(segments);
    }
}

关键修改说明

  • 新增file.ReadLine();:读取第一行(表头)后不做处理,直接跳过
  • 使用AddRange替代循环Add:简化代码同时提升性能
  • 简化分隔符定义:直接在Split方法中传入制表符'\t',无需单独变量

进阶优化(处理空行场景)

如果文件存在空行(表头或数据行),可以添加空行过滤逻辑:

var sepList = new List<string>();

using (var file = new StreamReader(docPath))
{
    string headerLine;
    // 跳过表头及表头前的空行
    while ((headerLine = file.ReadLine()) != null && string.IsNullOrWhiteSpace(headerLine))
    {
        // 循环跳过空行
    }

    string line;
    while ((line = file.ReadLine()) != null)
    {
        // 跳过数据区的空行
        if (string.IsNullOrWhiteSpace(line)) continue;
        var segments = line.Split('\t', StringSplitOptions.RemoveEmptyEntries);
        sepList.AddRange(segments);
    }
}

内容的提问来源于stack exchange,提问作者usama hussain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:17:13