在我的form1中,我有一个显示我的文件的列表框,然后单击列表框中的文件,它将泵送到form2进行更改。在我完成更改后,我想以原始名称保存文件。
但我的代码不起作用
错误显示“进程无法访问文件'U:\ test \ _ 111.txt',因为它正由另一个进程使用。”
这是form1
中列表框的代码 Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
myDirectory = "U:\test"
Dim myFile As String = myDirectory & "\" & ListBox1.SelectedItem & ".txt"
Dim sr As IO.StreamReader = IO.File.OpenText(myFile)
Form2.ListBox1.Items.Clear()
Do Until sr.EndOfStream
Form2.ListBox1.Items.Add(sr.ReadLine)
Loop
Form2.ShowDialog()
End Sub
这是我的保存按钮的代码
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Using SW As New IO.StreamWriter("U:\test\" & Form1.ListBox1.SelectedItem & ".txt", True)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End Sub
答案 0 :(得分:0)
在StreamWriter构造函数
中将append选项更改为false Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Using SW As New IO.StreamWriter("U:\test\" & Form1.ListBox1.SelectedItem & ".txt", False)
For Each itm As String In Me.ListBox1.Items
SW.WriteLine(itm)
Next
End Using
End Sub
答案 1 :(得分:0)
错误显示“进程无法访问文件'U:\ test \ 111.txt' 因为它正被另一个进程使用。“
您应首先在ListBox1_SelectedIndexChanged
关闭已打开的文件句柄。
sr.Close()