我正在尝试将一个列表框的内容保存到txt文件中,然后将其打开并将其打印到第二个列表框中。我已经完成了大部分工作,但我的实际文件不是txt文件。你能告诉我如何使用我的代码将文件变成txt文件吗?如果这不可能,你能告诉我一个可以的代码吗?
Private Sub LoadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LoadButton.Click
If OpenFD.ShowDialog() = DialogResult.OK Then
Dim lines = File.ReadAllLines(OpenFD.FileName)
ListBox2.Items.Clear()
ListBox2.Items.AddRange(lines)
End If
End Sub
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
If SaveFD.ShowDialog() = DialogResult.OK Then
Using Writer = New StreamWriter(SaveFD.FileName)
For Each o As Object In ListBox1.Items
Writer.WriteLine(o)
Next
End Using
End If
End Sub
答案 0 :(得分:2)
您可以使用File.WriteAllText
方法(以及字符串构建器)。我的意见是,这是更清晰的代码。
Private Sub SaveButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveButton.Click
If SaveFD.ShowDialog() = DialogResult.OK Then
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\mypath\output.txt", sb.ToString())
End If
End Sub