Vb.net System.IO.StreamReader空路径名不合法

时间:2011-09-30 10:38:28

标签: vb.net streamreader

我遇到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

程序启动时,故障为“空路径名称不合法”。

如何解决这个错误?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

你写道:

Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)

但你需要使用

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

如果您没有执行打开的文件对话框,则不会显示对话框本身,并且包含的​​文件名为空!!

<强>编辑:
我编辑我的帖子以反映您在评论中提到的内容:

Dim File_Directory As OpenFileDialog = New OpenFileDialog()
File_Directory.Filename = initial_file_name
Dim objReader As New System.IO.StreamReader(File_Directory.FileName)

或更好

Dim File_Directory As OpenFileDialog = New OpenFileDialog()
Dim objReader As New System.IO.StreamReader(initial_file_name)

答案 1 :(得分:0)

Hans Passant关于 As New 的评论是正确的。您不应将StreamReader创建为全局变量。在准备好使用它之前不要创建它。在StreamReader的情况下,您应该在Using块中实例化它:

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

通常,您应该尽量避免使用全局变量,并将它们声明为接近您将使用它们的位置。