这是我需要做的,我点击openfile按钮并打开openfile对话框。我打开一个文本文件,它会显示在informationbox.text字段中,同时我想在该文件中搜索一个ID号并将其显示在IDbox.text字段中。 我搜索过其他论坛,但他们只是使用替换方法或其他我不了解的方法。它变得太混乱了。
这就是我到目前为止 -
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
InformationBox.Text = oReader.ReadToEnd
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
oReader.Close()
End If
IDBox.Text = ""
Label11.Text = OpenFileDialog1.FileName
End Sub
textfile示例:
客户名称:姓名
客户姓氏:姓氏
身份证号码:12345678910
记录编号:001
客户地址:地址
有人可以帮我吗?
答案 0 :(得分:0)
在您的示例代码中,您使用StreamReader
来读取文本文件。
Streams的“缺点”是你必须手动管理他们的处理
在您的示例中,如果oReader.ReadToEnd
中发生错误,则不会点击行oReader.Close
,并且Stream可能会保持不受干扰,从而导致麻烦。
因此,您最好将您的Stream封装在Using
范围内(另一种选择是使用静态System.IO.File.ReadAllLines|ReadAllText
方法)。
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'Dim oReader As StreamReader <-- DELETE THIS
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
'MY CODE STARTS HERE:
Dim customerInfo As String
Using sr = New StreamReader(OpenFileDialog1.FileName, True)
customerInfo = sr.ReadToEnd()
End Using 'Close the stream early since we have all data needed
'Write all lines into a string array
Dim lines As String() = customerInfo.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'Get the line where the ID Number is in
Dim idLine As String = lines.Where(Function(l) l.StartsWith("ID number")).FirstOrDefault()
Dim id As String = String.Empty
If Not String.IsNullOrEmpty(idLine) Then
Dim aIdLine() = idLine.Split(":"c) 'Split the ID line by :
If aIdLine.Length >= 1 Then
id = aIdLine(1) 'This should be the actual ID
End If
End If
'Set UI
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
InformationBox.Text = customerInfo
IDBox.Text = id
Label11.Text = OpenFileDialog1.FileName
End If