尝试使用filemode.open和fileaccesss.read(必须)使用vb FileStream打开txt文件。
但是我不断收到“空路径名不合法”,我不确定为什么。
完整代码:
Private Sub tsmOpen_Click(sender As Object, e As EventArgs) Handles tsmOpen.Click
Dim OpenFile As New OpenFileDialog
Dim filePath As String = OpenFile.FileName
Dim fileRead As New FileStream(filePath, FileMode.Open, FileAccess.Read)
OpenFile.Filter = "Text Files (*.txt)|*.txt"
OpenFile.Title = "Open Text Files"
OpenFile.ShowDialog()
Try
Dim Read As New StreamReader(filePath)
rtxtMain.Text = Read.ReadToEnd
Catch ex As Exception
End Try
End Sub
答案 0 :(得分:1)
当用户关闭OpenFileDialog时,您不处理事件。
首先,您需要向用户询问文件,如果ShowDialog()
是DialogResult
,则调用OK
方法来检索文件。
然后,在指定的路径,创建模式和读/写权限中使用FileStream
打开文件。
我正在实现Using
语句以在使用完之后处置对象。
Dim OpenFile As New OpenFileDialog
OpenFile.Filter = "Text Files (*.txt)|*.txt"
OpenFile.Title = "Open Text Files"
If OpenFile.ShowDialog() = DialogResult.OK Then
Using fileReader = New FileStream(OpenFile.FileName, FileMode.Open, FileAccess.Read)
Using streamReader = New StreamReader(fileReader)
rtxtMain.Text = streamReader.ReadToEnd()
End Using
End Using
End If
另一种更简单的方法是ReadAllText类中的File方法:
Dim OpenFile As New OpenFileDialog With {
.Filter = "Text Files (*.txt)|*.txt",
.Title = "Open Text Files"
}
If OpenFile.ShowDialog() = DialogResult.OK Then
rtxtMain.Text = File.ReadAllText(OpenFile.FileName)
End If