StreamWriter写入文本文件中途停止 内容截断仅输出部分数据求助
问题根因
你遇到的两个核心问题直接导致了输出异常:
- StreamWriter 缓冲区未刷入磁盘:StreamWriter 属于带缓冲的IO对象,默认只有缓冲区写满、对象被释放/销毁时才会将内存中的内容写入磁盘。你当前代码没有对
StreamWriter做资源释放,循环结束后缓冲区剩余的内容没有落地,就会出现内容缺失、最后一条数据截断的问题。 - 循环内修改遍历集合导致遍历异常:你在
For Each遍历list的循环内部,重新给list赋值了排序后的新集合,这会破坏枚举器的遍历逻辑,导致部分元素未被遍历,这就是14条数据仅输出9条的原因。同时你的排序逻辑存在错误:OrderBy(Function(x) item.Submitters_First_Name_First)中用的是循环变量item的字段而非遍历元素x的字段,相当于所有元素的排序键完全相同,排序毫无意义。
修正后的代码
Using resource As New DevelopmentEntities ' 先查询、排序数据,不要在循环内修改遍历集合 Dim list As List(Of ContactU) = resource.ContactUs _ .OrderBy(Function(x) x.Submitters_First_Name_First) _ .ToList() ' 给StreamWriter套Using块,执行完自动释放、刷缓冲区到磁盘 Using sw As StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(outputpath & "Web_ContactUs_" & countValue & ".txt", True) For Each item In list countValue = countValue + 1 If Not String.IsNullOrEmpty(item.Entry_Id?.ToString()) Then Dim ssnValue = "UANPF" & item.Last_4_of_SSN.Trim() ' 直接格式化日期为字符串,避免多余的类型转换 Dim entry_date As String = CDate(item.Entry_Date.TrimEnd()).ToString("MM/dd/yyyy") Dim concatinatedFilepath = textfilepath & item.Submitters_First_Name_First.Replace(" ", "_").Trim() _ & "_" & item.Submitters_Last_Name_Last.Replace(" ", "_").Trim() _ & "_" & item.Last_4_of_SSN.Trim() _ & "_" & countValue Dim print = filetype & "|" & concatinatedFilepath & ".txt" & "|" & ssnValue & "|" & incoming & "|" & addresschange & "|" & entry_date & "|" & ITP sw.WriteLine(print) End If Next End Using End Using
额外优化说明
- 字符串前后去空格可以直接用
Trim()方法,不需要分开调用TrimStart()+TrimEnd() - 判空可以用
String.IsNullOrEmpty()更严谨,避免空引用异常 - 日期转换直接输出格式化后的字符串即可,不需要先赋值给Date类型变量再隐式转换为字符串,避免格式异常
内容的提问来源于stack exchange,提问作者user12280303
相关产品推荐
相关产品推荐

