【问题标题】:Loading Comma Delimited Text file into a Dictionary将逗号分隔的文本文件加载到字典中
【发布时间】:2012-01-23 23:54:46
【问题描述】:

我想将逗号分隔的文本文件 (PracInfo.txt) 的内容添加到 Form_Load 上的字典中。文件内容如下:

wlvc,coadmin
mrmd,thadmin
ccoa,oaadmin
bfhl,bfadmin
trty,tradmin
nppp,npadmin

例如,我希望 wlvc 为键,coadmin 为对应的值。我到目前为止的代码如下:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim sr As New StreamReader("C:\Programming files\PracInfo.txt")
        Dim openWith As New Dictionary(Of String, String)

        Do While sr.Peek <> -1
          strHold = sr.ReadLine()

          ' here I would like to use the String.Split method on strHold and then put that into the Dictionary using Dictionary.Add(Key,Value) but not sure how to do this????

        Loop    
    End Sub
End Class

在此问题上的任何帮助将不胜感激!谢谢

【问题讨论】:

    标签: vb.net string dictionary


    【解决方案1】:

    这个没有测试,只是伪代码

    Do While sr.Peek <> -1
        Dim lineArray As String() = sr.ReadLine().Split(",")
        If lineArray.Length = 2 Then
            openWith.Add(lineArray(0),lineArray(1))
        End If
    Loop  
    

    【讨论】:

      【解决方案2】:

      试试这个:

          Do While sr.Peek <> -1
              Dim line As String() = sr.ReadLine().Split(",")
              openWith.Add(line(0), line(1))
          Loop
      

      这会将一行读入数组。数组将以逗号分隔。然后,您可以分别引用第 0 个和第 1 个元素作为键和值。

      【讨论】:

        【解决方案3】:

        您可以使用静态方法File.ReadAllLines("filename.txt"),它将返回一个字符串数组,您可以在其上迭代和foreach元素,使用.Split()分隔逗号分隔的值,然后将它们添加到您的字典中。

        【讨论】:

        • 这取决于文本文件有多大,这是否是一个好主意。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 2019-04-05
        • 1970-01-01
        相关资源
        最近更新 更多