从文本文件中读取变量并创建表

时间:2012-08-07 13:27:51

标签: asp.net vb.net arrays vbscript

我有这段代码

'Open a file for reading
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
Dim variableArray(20) As String
objStreamReader = File.OpenText(filePath)

'Read one line at a time
Dim someString As String
Dim variableNum As Integer = 0
'Iterate through lines
While objStreamReader.Peek() <> -1
    someString = objStreamReader.ReadLine()
    variableArray(variableNum) = someString
    variableNum = variableNum + 1
End While
For Each line As String In variableArray

Next
objStreamReader.Close()

我有一个vbscript,它将结果输出到一个日志文件中,附加在每一行上并用“|”分隔只有两列。

以下是VBScript代码的片段

f1.WriteLine("Server Name " & "|" & strName)
f1.WriteLine("OS Name: " & "|" & strCaption)
f1.WriteLine("OS Version: " & "|" & strVersion
f1.WriteLine("CSD Version: " & "|" & strCSDVer
f1.WriteLine("Serial Number: " & "|" & strSerial

如何让我的代码的For Each部分读取它,将其拆分,然后创建一个显示结果的表。

2 个答案:

答案 0 :(得分:1)

考虑到你需要来自variableArray的两个值来向表中添加一个新行,我会做一个For..Next循环(踩2)而不是For ...每个:

Dim myTable As New Table
Dim loopCount As Integer

For loopCount = 0 To variableNum Step 2

    Dim myRow As New TableRow
    Dim myCell1 As New TableCell
    Dim myCell2 As New TableCell

    myCell1.Text = variableArray(loopCount)
    myCell2.Text = variableArray(loopCount + 1)
    myRow.Cells.Add(myCell1)
    myRow.Cells.Add(myCell2)
    myTable.Rows.Add(myRow)

Next

由于您已经将数组中的元素数量存储在“variableNum”中,因此您可以从0循环到该值,步进2。每次迭代,您将使用当前和下一个值创建两个单元格数组中的变量。然后,这些单元格将被添加到一行,然后将其添加到表格中。

答案 1 :(得分:1)

声明一个DataTable

Dim table As DataTable = new DataTable("MyTable")

现在在Foreach中:

Dim LineArray() As String = Split(line, "|") 'This will break apart each line into its two parts
'Now add each item of LineArray to the datatable. AKA
Dim column As DataColumn = new DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = LineArray(0)
column.ReadOnly = True
column.Unique = True
table.Columns.Add(column)

Dim row As DataRow 
row = table.NewRow()
row(LineArray(0)) = LineArray(1)
table.Rows.Add(row)

我不知道你想要实现的整个逻辑,但这应该给你一个良好的开端。它基本上取第一列并将其设置为表中的列,然后取第二列并使其成为行值。

一旦构建了DataTable,就可以将它绑定到一个GridView,它在HTML意义上就是一个表格。

希望这有帮助。