文本行长度校验场景下,如何仅在错误文件首行写入时添加头部说明?
解决错误文件头部仅添加一次的问题
我来帮你搞定这个需求!你只需要添加一个布尔标记变量来跟踪是否已经写入过错误文件的头部说明,这样就能确保只有当第一条超长行出现时才添加这些提示信息。
修改后的完整代码:
//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
相关产品推荐
相关产品推荐

