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

C#读取文本文件时如何提取两个指定分隔标记之间的内容

实现方案

核心逻辑通过状态开关判定区间边界,遍历文件行时动态开启/关闭内容收集,不需要复杂的正则匹配,性能和可读性都更高。

实现步骤

  1. 把读取到的文件行改为类级别的字段,避免重复读取磁盘文件
  2. 在ReadAdvertisingTest方法中新增收集状态标记、起止标记匹配规则
  3. 遍历行时匹配到起始标记就开启收集,匹配到结束标记就终止遍历,中间所有行直接存入结果集

完整代码示例

// 类级别字段,存储读取到的文件所有行,供全局调用
private string[] _fileLines;

protected void Page_Load(object sender, EventArgs e)
{
    string file = "My Text File.txt";
    string filePath = Server.MapPath(file);
    if (File.Exists(filePath))
    {
        _fileLines = File.ReadAllLines(filePath);
    }
    
    // 原有定位逻辑保持不变,优化冗余的Replace操作
    if (_fileLines != null)
    {
        foreach (string s in _fileLines)
        {
            if (s.Contains("This is my text"))
            {
                btnText.Text = "Heading 1";
                btnText.OnClientClick = ReadAdvertisingTest();
            }
            else if (s.Contains("This is my failed text"))
            {
                lblError.Text += "\nHeading 2";
            }
        }
    }
}

private string ReadAdvertisingTest()
{
    if (_fileLines == null || _fileLines.Length == 0)
        return string.Empty;
    
    List<string> resultLines = new List<string>();
    // 收集状态开关,默认关闭
    bool shouldCapture = false;
    // 起止标记可根据需求自行修改
    const string startMarker = "<== Line Break ==> (1)";
    const string endMarker = "<== Line Break ==> (4)";

    foreach (string line in _fileLines)
    {
        // 匹配到起始标记,开启收集,当前起始标记本身不加入结果
        if (line.Trim() == startMarker)
        {
            shouldCapture = true;
            continue;
        }

        // 匹配到结束标记,直接终止遍历,结束标记本身不加入结果
        if (line.Trim() == endMarker && shouldCapture)
        {
            break;
        }

        // 收集状态开启时,将当前行加入结果集
        if (shouldCapture)
        {
            resultLines.Add(line);
        }
    }

    // 如果是前端HTML展示,可以把Environment.NewLine换成<br/>实现换行效果
    return string.Join(Environment.NewLine, resultLines);
}

注意事项

  • 标记匹配时加了Trim()处理,可以兼容标记前后有多余空格的场景
  • 如果需要动态调整提取区间,把startMarker和endMarker改为方法入参即可
  • 输出内容如果要显示在前端页面,记得把换行符替换为HTML的<br/>标签,否则换行不会生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:57:00