我在尝试阅读文本文件时遇到错误

时间:2015-12-21 16:00:22

标签: vb.net

带错误的屏幕截图:

enter image description here

实际的错误讯息:

  

ArgumentException:已添加具有相同键的项目。

我在stackoverflow上学到了一些东西,当我使用它时它起作用,但当我在另一个项目中使用它时,我得到了它。

以下是您想要复制并测试它的代码。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    If My.Computer.FileSystem.FileExists(path_proporties_file) Then
        Dim lstSettings As New Dictionary(Of String, String)

        'Loop through each line.
        For Each strLine As String In IO.File.ReadAllLines(path_proporties_file)

            'Ignore empty lines and comments.
            If strLine.Length > 0 AndAlso strLine.Substring(0, 1) <> "#" Then

                'Split the Key from the Value.
                Dim LstKeyValue As List(Of String) = strLine.Split("=").ToList()

                'Some additional filtering of bad data.
                If LstKeyValue.Count = 2 Then

                    'Add to the Dictionary instance.
                    lstSettings.Add(LstKeyValue(0), LstKeyValue(1))

                End If

            End If

        Next

        Dim item_1_name = CStr(lstSettings("item_1_name"))
        Dim item_1_path = CStr(lstSettings("item_1_path"))
        Dim item_1_enabled = CBool(lstSettings("item_1_enabled"))

        Dim item_2_name = CStr(lstSettings("item_2_name"))
        Dim item_2_path = CStr(lstSettings("item_2_path"))
        Dim item_2_enabled = CBool(lstSettings("item_2_enabled"))

        Dim item_3_name = CStr(lstSettings("item_3_name"))
        Dim item_3_path = CStr(lstSettings("item_3_path"))
        Dim item_3_enabled = CBool(lstSettings("item_3_enabled"))

        Dim item_4_name = CStr(lstSettings("item_4_name"))
        Dim item_4_path = CStr(lstSettings("item_4_path"))
        Dim item_4_enabled = CBool(lstSettings("item_4_enabled"))

        Dim item_5_name = CStr(lstSettings("item_5_name"))
        Dim item_5_path = CStr(lstSettings("item_5_path"))
        Dim item_5_enabled = CBool(lstSettings("item_5_enabled"))

    Else
        MessageBox.Show("Error: Proporties file cannot be found")
    End If
End Sub

对不起,如果它是一个愚蠢的问题,但我查了一下,我找不到任何东西。

1 个答案:

答案 0 :(得分:1)

您收到的错误中的消息非常清楚:

  

已添加具有相同键的项目。

Dictionary.Add明确记录了这种行为。

所以当你这样做时:

lstSettings.Add(LstKeyValue(0), LstKeyValue(1))

...如果lstSettings字典已经具有LstKeyValue(0)值,则该语句将抛出此异常。它不会让你两次添加相同的键值。

所以,显然,你的属性文件在某处有重复的键。你必须确定如何处理这种情况。

相关问题