这段代码有什么问题?我想使用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
现在发生的事情是,当我双击某个文件或按下打开时,它会继续打开一个新的资源管理器窗口。当我退出那些窗户时它就会崩溃。谢谢你的帮助!
答案 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