Форум программистов, компьютерный форум, киберфорум
Visual Basic .NET
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/18: Рейтинг темы: голосов - 18, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 05.05.2011
Сообщений: 33

Чтение ini-file в Dictionary

15.04.2014, 15:20. Показов 3666. Ответов 5
Метки нет (Все метки)

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

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

вот это отдельным классом
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
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
вот это в форме прописано
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
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]
Миниатюры
Чтение ini-file в Dictionary  
Вложения
Тип файла: 7z WindowsApplication8.7z (52.1 Кб, 54 просмотров)
0
Лучшие ответы (1)
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
15.04.2014, 15:20
Ответы с готовыми решениями:

Картинки в ini-file. Не верные чтение или запись?
При чтении предварительно записанных изображений из ini-файла в TImage картинка в формате BMP появляется в виде черного квадрата Малевича, ...

Сохранение в ini и чтение из ini собственных типов данных и сохранение комментариев
Доброго времени суток. 1. Допустим есть собственный тип, определяемый посредством Enum. Public Enum Mode As Integer None...

Ini-file
Скажите пожалуйста! Можно ли сохранять в Ini фаил данные типа float? Поясняю: мне необходимо сохранить настройки, которые в десятичных...

5
0 / 0 / 0
Регистрация: 05.05.2011
Сообщений: 33
16.04.2014, 11:20  [ТС]
ну пожааалуйста, помогите кто-нибудь
я уже совсем голову сломала
0
Строитель
 Аватар для Nord790
889 / 556 / 194
Регистрация: 01.04.2014
Сообщений: 610
Записей в блоге: 6
16.04.2014, 12:00
могу показать другой код для работы с INI файлами с использованием Dictionary
0
0 / 0 / 0
Регистрация: 05.05.2011
Сообщений: 33
16.04.2014, 12:01  [ТС]
Nord790, это было бы замечательно!))
0
Строитель
 Аватар для Nord790
889 / 556 / 194
Регистрация: 01.04.2014
Сообщений: 610
Записей в блоге: 6
18.04.2014, 07:58
Лучший ответ Сообщение было отмечено Памирыч как решение

Решение

исходник:
Кликните здесь для просмотра всего текста
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 'Создаём экзампляр объекта 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")

пример использование кода:
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 'Создаём экземпляр объекта 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")
что бы загрузить файл
VB.NET
1
 INIFile.Load(ИМЯ_ФАЙЛА)
Добавлено через 1 час 7 минут
ошибка. вот исходник:
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
0
Строитель
 Аватар для Nord790
889 / 556 / 194
Регистрация: 01.04.2014
Сообщений: 610
Записей в блоге: 6
19.04.2014, 03:07
или вот ещё:

Кликните здесь для просмотра всего текста
VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
Вложения
Тип файла: zip INIEditor.zip (115.3 Кб, 72 просмотров)
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
19.04.2014, 03:07
Помогаю со студенческими работами здесь

ini file
Задача состоит в том, чтобы в инифайл сохранять настройку столбца. Visible=0 ItemIndex=15 Но проблема в том, что когда выбираю...

Ini file
public class IniReader { private Properties iniFile; private String configurationFile = &quot;config.ini&quot;; public...

Ini file checkbox.checked
Form2.CheckBox1.Checked := ini.ReadBool('Param', '1',true); - выдает ошибку CheckBox1.Checked := ini.ReadBool('Param', '1',true); - все...

Запись в файл и чтение из файла Dictionary(Of T, V)
Привет народ подскажите пожалуйста как можно записать в фаил.txt, Dictionary(Of T, V) формата (22.10.2018, &quot;44444444444&quot;) и...

Чтение элементов объекта Scripting.Dictionary
Добрый вечер. Возникла проблема извлечения элементов из объекта Scripting.Dictionary. Так как приведение элемента Item словаря не возможно,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru