要將文件讀入String
變量,在VB.NET中,可以使用System.IO.File.ReadAllText()
函數。一個例子是:
Imports System.IO '// placed at the top of the file'
'// some code'
Dim calculationText As String
calculationText = File.ReadAllText("calculations.txt") '// gets all the text in the file'
其中"calculations.txt"
是文件名。
到下一點 - 要允許用戶加載他們選擇的文件,可以使用OpenFileDialog
類型。舉個例子:
Dim fileName As String
Dim openDlg As OpenFileDialog
openDlg = New OpenFileDialog() '// make a new dialog'
If openDlg.ShowDialog() = DialogResult.OK Then
'// the user clicked OK'
fileName = openDlg.FileName '// openDlg.FileName is where it keeps the selected name'
End If
結合這一點,我們得到:
Imports System.IO
'// other code in the file'
Dim fileName As String
Dim openDlg As OpenFileDialog
openDlg = New OpenFileDialog() '// make a new dialog'
If openDlg.ShowDialog() = DialogResult.OK Then
'// the user clicked OK'
fileName = openDlg.FileName
End If
Dim calculationText As String
calculationText = File.ReadAllText(fileName)
現在,我們需要處理的輸入。首先,我們需要列出十進制數字。接下來,我們把一切都在文件中是一些在列表中:
Dim numbers As List(Of Decimal)
numbers = New List(Of Decimal)() '// make a new list'
Dim fields() As String
fields = calculationText.Split(" ") '// split all the text by a space.'
For Each field As String in fields '// whats inside here gets run for every thing in fields'
Dim thisNumber As Decimal
If Decimal.TryParse(field, thisNumber) Then '// if it is a number'
numbers.Add(thisNumber) '// then put it into the list'
End If
Next
這將不包括在列表中Calculated Concentrations
或?????
。對於可用代碼,只需組合第二個和最後一個代碼示例。
編輯:迴應下面的評論。
隨着List
對象,你可以索引他們像這樣:
Dim myNumber As Decimal
myNumber = numbers(1)
你並不需要使用Item
屬性。此外,它顯示在消息框中的時候,你需要把它變成一個String
型第一,是這樣的:
MsgBox(myNumber.ToString())
@人-B哎你的代碼不能正常工作,它不是解析 – 2009-06-14 19:23:17