从文本文件中读取特定值

时间:2015-08-30 21:23:00

标签: vb.net file text streamreader

我有以下可视基本代码,它是自定义类的一部分。我想要一种简单有效的方法(使用少量计算机资源)将“value1”值(100)分配给“_field1”,将“value2”值(8)分配给“_field2”等。任何好主意?感谢

Private Sub readcrnFile()
    'read files and assing values to the properties
    Dim sr As New IO.StreamReader(_fileName)

    _field1 = sr.ReadToEnd()
    _field2 = sr.ReadToEnd()
    _field3 = sr.ReadToEnd()

    sr.Close()

End Sub

其中_fileName是文本文件的完整路径,如下所示:

  

value1:100

     

value2:8

     

value3:80

2 个答案:

答案 0 :(得分:1)

Private Sub readcrnFile()
    Dim lines = File.ReadLines(_fileName)
    For Each line In lines
        Dim val = line.Split(":")(1).Trim
        'do something with val?
    Next
End Sub

返回字典很简单:

Private Sub readcrnFile()
    Dim dict = File.ReadLines(_fileName).Select(Function(line) line.Split(":")).ToDictionary(Function(parts) parts(0).Trim, Function(parts) parts(1).Trim)
    Debug.WriteLine(dict("value1")) 'will print 100
End Sub

答案 1 :(得分:0)

将您的body { background-color: #b5a789; font-family: Georgia, "Times New Roman", Times, serif; font-size: small; margin: 0px; display: table; } #header { background-color: #675c47; margin: 10px; height: 108px; } #main { background: #efe5d0 url(images/background.gif) top left; font-size: 105%; padding: 15px; margin: 0px 10px 10px 10px; width: 420px; display: table-cell; } #sidebar { background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%; padding: 15px; margin: 0px 10px 10px 10px; width: 300px; display: table-cell; float: right; } #footer { background-color: #675c47; color: #efe5d0; text-align: center; padding: 15px; margin: 10px; font-size: 90%; clear: left; } h1 { font-size: 120%; color: #954b4b; } .slogan { color: #954b4b; } .beanheading { text-align: center; line-height: 1.8em; } a:link { color: #b76666; text-decoration: none; border-bottom: thin dotted #b76666; } a:visited { color: #675c47; text-decoration: none; border-bottom: thin dotted #675c47; } #allcontent { width: 800px; padding-top: 5px; padding-bottom: 5px; background-color: #675c47; } _field1_field2变量更改为_field3(即名为List(Of String))并使用其索引访问每个字段({{ 1}},fieldfield(0))。

field(1)