0

在我的 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
4

2 回答 2

0

错误提示“该进程无法访问文件 'U:\test\111.txt',因为它正被另一个进程使用。”

您应该ListBox1_SelectedIndexChanged首先关闭打开的文件句柄 ..

sr.Close()
于 2013-07-25T02:46:27.663 回答
0

Change the append option to false in the StreamWriter constructor

 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
于 2013-07-25T01:08:35.633 回答