StreamWriter 在写入文本文件中途停止写入
Posted
技术标签:
【中文标题】StreamWriter 在写入文本文件中途停止写入【英文标题】:StreamWriter stops writing in the meddle of writing to a text file halfway 【发布时间】:2021-12-19 17:57:13 【问题描述】:我有一个包含 14 个来自 SQL Server 表的值的列表,我正在循环使用 WriteLine 将值传递给 StreamWriter 对象,以便在文本文件中以所需格式写入值。我的问题是,在调试时,我可以看到所有值都添加到我的打印变量中;但是,当循环完成时,它只打印 9 个值,第 9 个值在文本文件中被剪切。请参考我的截图。
Using resource As New DevelopmentEntities
Dim sw As StreamWriter
Dim list As New List(Of ContactU)
list = resource.ContactUs.ToList()
sw = My.Computer.FileSystem.OpenTextFileWriter(outputpath & "Web_ContactUs_" & countValue & ".txt", True)
For Each item In list
list = list.OrderBy(Function(x) item.Submitters_First_Name_First).ToList()
countValue = countValue + 1
If Not item.Entry_Id.ToString Is "" Then
Dim valueItem = list
Dim ssnValue = "UANPF" & item.Last_4_of_SSN.TrimStart.TrimEnd
Dim raw_date As Date = item.Entry_Date.TrimEnd
Dim entry_date As Date = raw_date.ToString("MM/dd/yyyy")
Dim concatinatedFilepath = textfilepath & item.Submitters_First_Name_First.Replace(" ", "_").TrimStart.TrimEnd _
& "_" & item.Submitters_Last_Name_Last.Replace(" ", "_").TrimStart.TrimEnd _
& "_" & item.Last_4_of_SSN.TrimStart _
& "_" & countValue
Dim print = filetype &
"|" & concatinatedFilepath &
".txt" &
"|" & ssnValue &
"|" & incoming &
"|" & addresschange &
"|" & entry_date &
"|" & ITP
sw.WriteLine(print)
Else
'Do nothing will clear invalid data
End If
Next
End Using
【问题讨论】:
你在哪里关闭sw
?
@Steeeve 对不起,我以为我捕获了顶部,我使用的是 Using 语句。我也复制了我的代码。如果您需要整个方法,请告诉我。
我看不到 sw
的任何使用块
@Steeeve 哦,天哪!捂脸!我刚刚意识到我没有 sw.flash() sw.Close() 方法。你是救命稻草……哈哈,顺便说一句,我需要 sw.flash 吗?
如果将 sw 放在 using 块中,则不需要 Flush()
或 Close()
【参考方案1】:
试试这个:
Using resource As New DevelopmentEntities
Dim sw As StreamWriter
Dim list As New List(Of ContactU)
list = resource.ContactUs.ToList()
sw = My.Computer.FileSystem.OpenTextFileWriter(outputpath & "Web_ContactUs_" & countValue & ".txt", True)
For Each item In list
list = list.OrderBy(Function(x) item.Submitters_First_Name_First).ToList()
countValue = countValue + 1
If Not item.Entry_Id.ToString Is "" Then
Dim valueItem = list
Dim ssnValue = "UANPF" & item.Last_4_of_SSN.TrimStart.TrimEnd
Dim raw_date As Date = item.Entry_Date.TrimEnd
Dim entry_date As Date = raw_date.ToString("MM/dd/yyyy")
Dim concatinatedFilepath = textfilepath & item.Submitters_First_Name_First.Replace(" ", "_").TrimStart.TrimEnd _
& "_" & item.Submitters_Last_Name_Last.Replace(" ", "_").TrimStart.TrimEnd _
& "_" & item.Last_4_of_SSN.TrimStart _
& "_" & countValue
Dim print = filetype &
"|" & concatinatedFilepath &
".txt" &
"|" & ssnValue &
"|" & incoming &
"|" & addresschange &
"|" & entry_date &
"|" & ITP
sw.WriteLine(print)
Else
'Do nothing will clear invalid data
End If
Next
sw.Close()
End Using
【讨论】:
以上是关于StreamWriter 在写入文本文件中途停止写入的主要内容,如果未能解决你的问题,请参考以下文章
c# StreamWriter 应用中,我想每一行中写入两个不同性质的数据,该怎么写呢
StreamWriter 输出 ... 在 .txt 文件的末尾