Чтение 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] |
|
0
|