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

文本行长度校验场景下,如何仅在错误文件首行写入时添加头部说明?

解决错误文件头部仅添加一次的问题

我来帮你搞定这个需求!你只需要添加一个布尔标记变量来跟踪是否已经写入过错误文件的头部说明,这样就能确保只有当第一条超长行出现时才添加这些提示信息。

修改后的完整代码:

//Pass the file path and file name to the StreamReader and StreamWriter constructors
StreamReader sr = new StreamReader(inputFile);
StreamWriter sw = new StreamWriter(Dts.Connections["CE802CleanInput"].ConnectionString);
StreamWriter swe = new StreamWriter(Dts.Connections["CE802PreValidationErrors"].ConnectionString);

// 添加标记变量:记录是否已写入错误头部
bool hasWrittenErrorHeader = false;
int count = 0; // 补充count的声明,原代码中用到但未显式声明

//Read the first line
string line = sr.ReadLine();
while (line != null)
{
    int length = line.Length;
    if (length > 2033)
    {
        // 只有当还没写过头部时,才写入说明信息
        if (!hasWrittenErrorHeader)
        {
            swe.WriteLine("Some records have been rejected at the pre validation phase.");
            swe.WriteLine("Those records will not be included in the process.");
            swe.WriteLine("Please review the records below, fix and re submit if applicable.");
            swe.WriteLine("Input file: " + Dts.Connections["CE802Input"].ConnectionString.ToString());
            swe.WriteLine();
            // 标记头部已写入,避免重复输出
            hasWrittenErrorHeader = true;
        }
        // 写入当前错误行
        swe.WriteLine(line);
        count++;
    }
    if (length <= 2033)
    {
        sw.WriteLine(line);
    }
    line = sr.ReadLine();
}

// 记得手动关闭流释放资源,或者用using语句更安全
sr.Close();
sw.Close();
swe.Close();

逻辑说明:

  • 变量hasWrittenErrorHeader初始值为false,表示还未写入错误文件的头部说明。
  • 第一次遇到行长度超过2033的记录时,会执行头部信息的写入,同时把hasWrittenErrorHeader设为true。
  • 后续再遇到错误行时,因为hasWrittenErrorHeader已经是true,会直接跳过头部写入步骤,只写入错误行内容。

另外给你个小优化建议:推荐用using语句包裹流对象,这样可以自动释放资源,避免忘记关闭流导致的问题,示例如下:

using (StreamReader sr = new StreamReader(inputFile))
using (StreamWriter sw = new StreamWriter(Dts.Connections["CE802CleanInput"].ConnectionString))
using (StreamWriter swe = new StreamWriter(Dts.Connections["CE802PreValidationErrors"].ConnectionString))
{
    bool hasWrittenErrorHeader = false;
    int count = 0;
    string line = sr.ReadLine();
    while (line != null)
    {
        // 这里放原循环内的处理逻辑
        line = sr.ReadLine();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:05:38