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

StreamWriter コンストラクターで追加オプションを 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
于 2013-07-25T01:08:35.633 に答える