这个vb.net代码有什么问题?打开.txt文件

时间:2014-03-06 18:55:21

标签: vb.net

这段代码有什么问题?我想使用OpenFileDialog打开一个txt文件。

 Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    OpenFileDialog1.ShowDialog()
    Dim strTxtFileName As String = OpenFileDialog1.FileName
    If System.IO.File.Exists(strTxtFileName) Then
        Dim read As New System.IO.StreamReader(strTxtFileName)
        TextBox4.Text = read.ReadToEnd
        read.Close()
    End If
End Sub

现在发生的事情是,当我双击某个文件或按下打开时,它会继续打开一个新的资源管理器窗口。当我退出那些窗户时它就会崩溃。谢谢你的帮助!

1 个答案:

答案 0 :(得分:1)

将该代码放在差异处。我更喜欢使用块。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
 OpenFileDialog1.ShowDialog()
 Dim strTxtFileName As String = OpenFileDialog1.FileName
 If System.IO.File.Exists(strTxtFileName) Then
    Using read As New System.IO.StreamReader(strTxtFileName)
     TextBox4.Text = read.ReadToEnd
    End Using ' calls read.Close() for you
 End If
End Sub