I have a fault with System.IO.StreamReader.
Public Class Project
Dim merah As Integer
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
Dim Text_LineByLine As String
Private Sub BrowseFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BrowseFile.Click
File_Operations()
'Do While objReader.Peek() <> -1
Default_Operations()
MessageBox.Show(Text_LineByLine)
'Loop
End Sub
Sub File_Operations()
File_Directory.InitialDirectory = "C:\"
File_Directory.Filter = "All files (*.txt)|*.txt|All files (*.txt)|*.txt"
If File_Directory.ShowDialog() = DialogResult.OK Then
BrowserPath.Text = File_Directory.FileName
End If
End Sub
When the program starts, The faultis 'Empty path name is not legal.'
开发者_如何学GoHow to solve this fault?
Thanks for any helping.
You write:
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
but you need to use
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
If File_Directory.ShowDialog() = DialogResult.OK Then
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
Endif
If you don't execute your open file dialog, dialog itself is not shown and contained filename is empty!!
EDITED:
I edit my post to reflect what you asked in your comment:
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
File_Directory.Filename = initial_file_name
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)
or better
Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(initial_file_name)
Hans Passant's comment about As New is correct. You should not create your StreamReader as a global variable. Don't create it until you are ready to use it. And in the case of the StreamReader, you should instantiate it inside a Using block:
Imports System.IO
Sub Main()
Dim filename As String = someMethodThatGetsTheFilename()
Using objReader As New StreamReader(filename)
'Use the StreamReader here
End Using 'This line will automatically close and dispose of the StreamReader
End Sub
In general, you should try to avoid using global variables and declare them close to where you will be using them.
精彩评论