MyTetra Share
Делитесь знаниями!
Чтение ini-file в Dictionary - Visual Basic .NET
Время создания: 24.03.2018 23:49
Раздел: VB
Запись: xintrea/mytetra_db_adgaver_new/master/base/15219245536myokl2zys/text.html на raw.githubusercontent.com

Чтение ini-file в Dictionary - Visual Basic .NET

15.04.2014, 15:20. Просмотров 1528. Ответов 5

Метки нет (Все метки)


Мне нужно прочитать ini файл в Dictionary(Of String, String). Алгоритм для чтения есть, программа вроде рабочая - но файл считывать не хочет (говорит что не находит его).

Помогите пожалуйста ... бьюсь что-то, но никак не идет

вот это отдельным классом

Imports System.IO

 
Public Class inifile
    '------------------------------------------------
    ' Name:
    '
    ' inifile.vb
    '
    ' Description:
    '
    ' Simple minded implementation of an inifile reader/writer class. The functionality is all
    ' here except that error checking is minimal, everythinig is case sensitive and there is
    ' no provision to maintain blank lines or comments.
    '
    ' Properties:
    '
    ' status - String - blank or a string indicating the nature of the error
    '
    ' Methods:
    '
    ' Read(filename)
    '
    ' Read the given inifile into memory
    '
    ' Write()
    '
    ' Write the in-memory inifile to the last read inifile on disk
    '
    ' Write(filename)
    '
    ' Write the in0memory inifile to the given file and make it the current file
    '
    ' GetValue(section,setting)
    '
    ' Return the value of the given setting in the given section
    '
    ' SetValue(section,setting,value)
    '
    ' Set the given setting in the given section to the given valaue (create as needed)
    '
    ' Delete(section)
    '
    ' Delete the given section and all of its settings
    '
    ' Delete(section,setting)
    '
    ' Delete the given setting ini the given section
    '
    ' Serialize()
    '
    ' Convert the in-memory inifile to a string (lines end with vbCrLf) with encryption
    '
    ' Serialize2()
    '
    ' Convert the in-memory inifile to a string (lines end with vbCrLf) without encryption
    '
    ' Notes:
    '
    ' The in-memory inifile is maintained as nested dictionaries. Each section is a dictionary
    ' where the key is the setting name and the value is the string value of the setting. The
    ' entire structure is also a dictionary where the key is the section name (including the [
    ' and ] delimiters) and the value is the dictionary of the associated settings.
 
    '------------------------------------------------
    Public status As String = ""
    Private m_inifile As New Dictionary(Of String, Dictionary(Of String, String))
    Private m_filename As String = ""
    Public Function GetValue(section As String, setting As String) As String
        'return the value of <setting> in [section]
        'return Nothing if not defined
        status = ""
        If Not m_inifile.ContainsKey(section) Then
            status = section & " not found"
            Return Nothing
        End If
        If Not m_inifile(section).ContainsKey(setting) Then
            status = section & setting & " not found"
            Return Nothing
        End If
        Return m_inifile(section)(setting)
    End Function
    Public Sub SetValue(section As String, setting As String, value As String)
        'set the value of <setting> in [section]
        status = ""
        'create [section] if not defined
        If Not section.StartsWith("[") Then
            section = "[" & section
        End If
        If Not section.EndsWith("]") Then
            section &= "]"
        End If
        If Not m_inifile.ContainsKey(section) Then
            m_inifile.Add(section, New Dictionary(Of String, String))
        End If
        'create <setting> if not defined and set value
        If Not m_inifile(section).ContainsKey(setting) Then
            m_inifile(section).Add(setting, value)
        Else
            m_inifile(section)(setting) = value
        End If
    End Sub
    Public Function Delete(section As String) As Boolean
        'delete the given section and all of its settings
        status = ""
        If Not m_inifile.ContainsKey(section) Then
            status = section & " not found"
            Return False
        End If
        m_inifile.Remove(section)
        Return True
    End Function
    Public Function Delete(section As String, setting As String) As Boolean
        'delete the given setting from the given section
        status = ""
        If Not m_inifile.ContainsKey(section) Then
            status = section & " not found"
            Return False
        End If
        If Not m_inifile(section).ContainsKey(setting) Then
            status = section & setting & " not found"
            Return False
        End If
        m_inifile(section).Remove(setting)
        Return True
    End Function
    Public Function Read(filename As String) As Boolean
        'read the given ini file
        Dim section As String = Nothing
        Dim setting As String = Nothing
        Dim value As String = Nothing
        Dim equals As Integer
        status = ""
        If Not My.Computer.FileSystem.FileExists(filename) Then
            status = filename & " not found"
            Return False
        End If
        'get rid of any existing entries
        m_inifile.Clear()
        m_filename = filename
        For Each line As String In System.IO.File.ReadAllLines(m_filename)
            'process either a section "[" or a setting
            If line.StartsWith("[") Then
                section = Trim(line)
                m_inifile.Add(section, New Dictionary(Of String, String))
            Else
                equals = InStr(line, "=")
                setting = Trim(line.Substring(0, equals - 1))
                value = Decrypt(Trim(line.Substring(equals)))
                m_inifile(section).Add(setting, value)
            End If
        Next
        Return True
    End Function
    Public Function Write(filename As String) As Boolean
        'write the inifile to the given filename and set filename as
        'the current inifile
        status = ""
        Try
            File.WriteAllText(filename, Serialize())
            m_filename = filename
        Catch ex As Exception
            status = ex.Message
            Return False
        End Try
        Return True
    End Function
    Public Function Write() As Boolean
        'write the inifile to the current file
        Return IIf(m_filename = "", False, Write(m_filename))
    End Function
    Public Function Serialize() As String
        'convert the in-memory inifile to a string
        Dim builder As New System.Text.StringBuilder
        For Each section As String In m_inifile.Keys
            builder.Append(section & vbCrLf)
            For Each setting As String In m_inifile(section).Keys
                builder.Append(setting & "=" & Encrypt(m_inifile(section)(setting)) & vbCrLf)
            Next
        Next
        Return builder.ToString
    End Function
    Public Function Serialize2() As String
        'convert the in-memory inifile to a string (no encryption)
        Dim builder As New System.Text.StringBuilder
        For Each section As String In m_inifile.Keys
            builder.Append(section & vbCrLf)
            For Each setting As String In m_inifile(section).Keys
                builder.Append(setting & "=" & m_inifile(section)(setting) & vbCrLf)
            Next
        Next
        Return builder.ToString
    End Function
End Class

вот это в форме прописано

Imports System.Security

Imports System.Security.Cryptography
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Text
 
Module EncryptDecrypt
    Public Function Encrypt(ByVal plainText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        Dim plainTextBytes As Byte() = Encoding.UTF8.GetBytes(plainText)
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        Dim symmetricKey As New RijndaelManaged()
        symmetricKey.Mode = CipherMode.CBC
        Dim encryptor As ICryptoTransform = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes)
        Dim memoryStream As New MemoryStream()
        Dim cryptoStream As New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length)
        cryptoStream.FlushFinalBlock()
        Dim cipherTextBytes As Byte() = memoryStream.ToArray()
        memoryStream.Close()
        cryptoStream.Close()
        Dim cipherText As String = Convert.ToBase64String(cipherTextBytes)
        Return cipherText
    End Function
    Public Function Decrypt(ByVal cipherText As String) As String
        Dim passPhrase As String = "yourPassPhrase"
        Dim saltValue As String = "mySaltValue"
        Dim hashAlgorithm As String = "SHA1"
        Dim passwordIterations As Integer = 2
        Dim initVector As String = "@1B2c3D4e5F6g7H8"
        Dim keySize As Integer = 256
        'Convert strings defining encryption key characteristics into byte
        'arrays. Let us assume that strings only contain ASCII codes.
        'If strings include Unicode characters, use Unicode, UTF7, or UTF8
        'encoding.
        Dim initVectorBytes As Byte() = Encoding.ASCII.GetBytes(initVector)
        Dim saltValueBytes As Byte() = Encoding.ASCII.GetBytes(saltValue)
        'Convert our ciphertext into a byte array.
        Dim cipherTextBytes As Byte() = Convert.FromBase64String(cipherText)
        'First, we must create a password, from which the key will be
        'derived. This password will be generated from the specified
        'passphrase and salt value. The password will be created using
        'the specified hash algorithm. Password creation can be done in
        'several iterations.
        Dim password As New PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations)
        'Use the password to generate pseudo-random bytes for the encryption
        'key. Specify the size of the key in bytes (instead of bits).
        Dim keyBytes As Byte() = password.GetBytes(keySize \ 8)
        'Create uninitialized Rijndael encryption object.
        Dim symmetricKey As New RijndaelManaged()
        'It is reasonable to set encryption mode to Cipher Block Chaining
        '(CBC). Use default options for other symmetric key parameters.
        symmetricKey.Mode = CipherMode.CBC
        'Generate decryptor from the existing key bytes and initialization
        'vector. Key size will be defined based on the number of the key
        'bytes.
        Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes)
        'Define memory stream which will be used to hold encrypted data.
        Dim memoryStream As New MemoryStream(cipherTextBytes)
        'Define cryptographic stream (always use Read mode for encryption).
        Dim cryptoStream As New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
        'Since at this point we don't know what the size of decrypted data
        'will be, allocate the buffer long enough to hold ciphertext;
        'plaintext is never longer than ciphertext.
        Dim plainTextBytes As Byte() = New Byte(cipherTextBytes.Length - 1) {}
        'Start decrypting.
        Dim decryptedByteCount As Integer = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length)
        'Close both streams.
        memoryStream.Close()
        cryptoStream.Close()
        'Convert decrypted data into a string.
        'Let us assume that the original plaintext string was UTF8-encoded.
        Dim plainText As String = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount)
        'Return decrypted string.
        Return plainText
    End Function
End Module
 
Public Class Form2
    '----------------------------------------------
    '
    ' Name:
    '
    ' IniReadWrite.vb
    '
    ' Description:
    '
    ' GUI front end for testing the inifile Class
    '
    '
    '----------------------------------------------
    Private ini As New inifile
    Private Sub UpdateDisplay()
        Me.Text = ini.status
        txtReadFile.Text = ini.Serialize2()
    End Sub
    Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
        ini.Read(txtReadFile.Text)
        UpdateDisplay()
    End Sub
    Private Sub btnWrite_Click(sender As System.Object, e As System.EventArgs) Handles btnWrite.Click
        If txtWriteFile.Text = "" Then
            ini.Write()
        Else
            ini.Write(txtWriteFile.Text)
            txtReadFile.Text = txtWriteFile.Text
            txtWriteFile.Text = ""
        End If
        UpdateDisplay()
    End Sub
    Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
        If txtSection.Text <> "" And txtSetting.Text <> "" And txtValue.Text <> "" Then
            ini.SetValue(txtSection.Text, txtSetting.Text, txtValue.Text)
            UpdateDisplay()
        Else
            MsgBox("you must enter values for section, setting and value")
        End If
    End Sub
    Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs) Handles btnDelete.Click
        Dim delim As Integer = InStr(txtDelete.Text, "]")
        If txtDelete.Text.StartsWith("[") And delim > 0 Then
            If txtDelete.Text.EndsWith("]") Then
                'delete section
                ini.Delete(txtDelete.Text)
            Else
                'delete setting
                Dim section As String = txtDelete.Text.Substring(0, delim)
                Dim setting As String = txtDelete.Text.Substring(delim)
                ini.Delete(section, setting)
            End If
            UpdateDisplay()
        Else
            MsgBox("delete string must contain a section as [section]")
        End If
    End Sub
 
End Class
 
интерфейс вот такой
[ATTACH]388771[/ATTACH]
 
программа вот
[ATTACH]388772[/ATTACH]				

  Вложения

WindowsApplication8.7z (52.1 Кб, 17 просмотров)

'====================================================================================================

исходник:


 'Создаём экзампляр объекта INIFile

        Dim INI As New INIFile
 
        'Добавляем в файл секцию например "[SECTION1]"
        With INI.AddSection("SECTION1")
            'Добавляем в эту секцию значение "VALUE1" с именем "KEY1"
            .Add("KEY1", "VALUE1")
            'Добавляем в эту секцию значение "VALUE2" с именем "KEY2"
            .Add("KEY2", "VALUE2")
            'Добавляем в эту секцию значение "VALUE3" с именем "KEY3"
            .Add("KEY3", "VALUE3")
        End With
 
        'Добавляем в файл секцию например "[SECTION2]"
        With INI.AddSection("SECTION2")
            'Добавляем в эту секцию значение "VALUE1" с именем "KEY1"
            .Add("KEY1", "VALUE1")
            'Добавляем в эту секцию значение "VALUE2" с именем "KEY2"
            .Add("KEY2", "VALUE2")
            'Добавляем в эту секцию значение "VALUE3" с именем "KEY3"
            .Add("KEY3", "VALUE3")
        End With
 
        'Узнаем какие секции у нас есть в файле и перечесляем их значения
        For Each key In INI.Keys
            For Each item In INI.Section(key).Keys
                Dim NameValue As String = item
                Dim DataValue As String = INI.Section(key)(NameValue)
                MsgBox(key & "\" & NameValue & " = " & DataValue)
            Next
        Next
 
        'Сохраняем в файл
        INI.Save("C:\example.ini")

пример использование кода:

 'Создаём экземпляр объекта INIFile 
        Dim INI As New INIFile
 
        'Добавляем в файл секцию например "[SECTION1]"
        With INI.AddSection("SECTION1")
            'Добавляем в эту секцию значение "VALUE1" с именем "KEY1"
            .Add("KEY1", "VALUE1")
            'Добавляем в эту секцию значение "VALUE2" с именем "KEY2"
            .Add("KEY2", "VALUE2")
            'Добавляем в эту секцию значение "VALUE3" с именем "KEY3"
            .Add("KEY3", "VALUE3")
        End With
 
        'Добавляем в файл секцию например "[SECTION2]"
        With INI.AddSection("SECTION2")
            'Добавляем в эту секцию значение "VALUE1" с именем "KEY1"
            .Add("KEY1", "VALUE1")
            'Добавляем в эту секцию значение "VALUE2" с именем "KEY2"
            .Add("KEY2", "VALUE2")
            'Добавляем в эту секцию значение "VALUE3" с именем "KEY3"
            .Add("KEY3", "VALUE3")
        End With
 
        'Узнаем какие секции у нас есть в файле и перечисляем их значения
        For Each key In INI.Keys
            For Each item In INI.Section(key).Keys
                Dim NameValue As String = item
                Dim DataValue As String = INI.Section(key)(NameValue)
                MsgBox(key & "\" & NameValue & " = " & DataValue)
            Next
        Next
 
        'Сохраняем в файл
        INI.Save("C:\example.ini")
что бы загрузить файл 
INIFile.Load(ИМЯ_ФАЙЛА)

ошибка. вот исходник:
Public Class INIFile
    Private ListSections As New Collections.Generic.Dictionary(Of String, Collections.Generic.Dictionary(Of String, String))
 
    Public Function AddSection(key As String) As Collections.Generic.Dictionary(Of String, String)
        Dim ValuesDictionary As New Collections.Generic.Dictionary(Of String, String)
        ListSections.Add(key, ValuesDictionary)
        Return ValuesDictionary
    End Function
 
    Public ReadOnly Property Count As Integer
        Get
            Return ListSections.Count
        End Get
    End Property
 
    Public Sub Remove(key As String)
        ListSections.Remove(key)
    End Sub
 
    Public ReadOnly Property Keys As String()
        Get
            Dim TKeys() As String = {}
            For Each n In ListSections.Keys
                ReDim Preserve TKeys(TKeys.Length)
                TKeys(TKeys.Length - 1) = n
            Next
            Return TKeys
        End Get
    End Property
 
    Public ReadOnly Property Section(key As String) As Collections.Generic.Dictionary(Of String, String)
        Get
            Return ListSections(key)
        End Get
    End Property
 
    Public Sub Clear()
        ListSections.Clear()
    End Sub
 
    Public Sub Save(FileName As String)
        Dim FileString As String = ""
        For Each SectionItem In ListSections
            Dim SectionName As String = String.Format("[{0}]", SectionItem.Key)
            FileString &= SectionName & vbNewLine
            For Each item In ListSections.Item(SectionItem.Key)
                Dim ValueData As String = String.Format("{0} = {1}", {item.Key, item.Value})
                FileString &= ValueData & vbNewLine
            Next
        Next
        IO.File.WriteAllText(FileName, FileString)
    End Sub
 
    Public Shared Function Load(FileName) As INIFile
        Dim Result As New INIFile
        Dim EndSection As Collections.Generic.Dictionary(Of String, String) = Nothing
        For Each Line In IO.File.ReadAllLines(FileName)
            Line = Line.Trim
            If Line.StartsWith("[") And Line.EndsWith("]") Then
                EndSection = Result.AddSection(Mid(Line, 2, Line.Length - 2))
            ElseIf Line Like "*=*" Then
                Dim Values As String() = Split(Line, "=")
                EndSection.Add(Values(0).Trim, Values(1).Trim)
            End If
        Next
        Return Result
    End Function
 
End Class
или вот ещё:
Public Class INIFile
    Private ListSections As New SectionsCollection
 
    Public Class SectionsCollection
        Private SCollection As New Collection
 
        Public Function Add(name As String) As ValuesCollection
            Dim Result As New ValuesCollection
            SCollection.Add({name, Result}, name)
            Return Result
        End Function
 
        Public Sub Remove(name As String)
            SCollection.Remove(name)
        End Sub
 
        Public Sub Clear()
            SCollection.Clear()
        End Sub
 
        Public ReadOnly Property Count As Integer
            Get
                Return SCollection.Count
            End Get
        End Property
 
        Public Function GetSection(name As String) As ValuesCollection
            Return SCollection.Item(name)(1)
        End Function
 
        Public ReadOnly Property Items As String()
            Get
                Dim Result() As String = {}
                For Each item In SCollection
                    ReDim Preserve Result(Result.Length)
                    Result(Result.Length - 1) = item(0)
                Next
                Return Result
            End Get
        End Property
 
    End Class
 
    Public Class ValuesCollection
        Private VCollection As New Collection
 
        Public Sub Add(key As String, value As String)
            VCollection.Add({key, value}, key)
        End Sub
 
        Public Sub Remove(key As String)
            VCollection.Remove(key)
        End Sub
 
        Public Sub Clear()
            VCollection.Clear()
        End Sub
 
        Public ReadOnly Property Count As Integer
            Get
                Return VCollection.Count
            End Get
        End Property
 
        Public ReadOnly Property Keys As String()
            Get
                Dim Result() As String = {}
                For Each item In VCollection
                    ReDim Preserve Result(Result.Length)
                    Result(Result.Length - 1) = item(0)
                Next
                Return Result
            End Get
        End Property
 
        Public ReadOnly Property Value(key As String) As String
            Get
                Return VCollection.Item(key)(1)
            End Get
        End Property
 
        Public ReadOnly Property Value(index As Integer) As String
            Get
                Return VCollection.Item(index + 1)(1)
            End Get
        End Property
    End Class
 
    Public Sub SaveFile(path As String)
        Using FileText = IO.File.CreateText(path)
            For Each item In Sections.Items
                FileText.WriteLine(String.Format("[{0}]", item))
                For Each key In Sections.GetSection(item).Keys
                    FileText.WriteLine(String.Format("{0} = {1}", {key,
                                                                   Sections.GetSection(item).Value(key)}))
                Next
            Next
        End Using
    End Sub
 
    Public Sub OpenFile(path As String)
        Sections.Clear()
        Dim VCol As ValuesCollection = Nothing
        For Each Line In IO.File.ReadAllLines(path)
            Line = Line.Trim
            If Line.StartsWith("[") And Line.EndsWith("]") Then
 
                VCol = Sections.Add(Mid(Line, 2, Line.Length - 2).Trim)
            ElseIf Line Like "*=*" Then
                If Not VCol Is Nothing Then
                    Dim keyName As String = Split(Line, "=")(0).Trim
                    Dim valueData As String = Split(Line, "=")(1).Trim
                    VCol.Add(keyName, valueData)
                End If
            End If
        Next
    End Sub
 
    Public Function Parse(str As String) As SectionsCollection
        Dim Result As New SectionsCollection
        Dim VCol As ValuesCollection = Nothing
        For Each Line In Split(str, vbNewLine)
            Line = Line.Trim
            If Line.StartsWith("[") And Line.EndsWith("]") Then
 
                VCol = Result.Add(Mid(Line, 2, Line.Length - 2).Trim)
            ElseIf Line Like "*=*" Then
                If Not VCol Is Nothing Then
                    Dim keyName As String = Split(Line, "=")(0).Trim
                    Dim valueData As String = Split(Line, "=")(1).Trim
                    VCol.Add(keyName, valueData)
                End If
            End If
        Next
        Return Result
    End Function
 
    Public ReadOnly Property Sections As SectionsCollection
        Get
            Return ListSections
        End Get
    End Property
End Class





Прикрепленные файлы:
Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования