C#读写INI文件

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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace SHSH.IniManage
{
/// <summary>
/// Ini文件管理器
/// </summary>
public class IniManage
{
#region API声明

/// <summary>
/// 获取所有节点名称(Section)
/// </summary>
/// <param name="lpszReturnBuffer">存放节点名称的内存地址,每个节点之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32")]
private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName);

/// <summary>
/// 获取某个指定节点(Section)中所有KEY和Value (乱码。。。。。。)
/// </summary>
/// <param name="lpAppName">节点名称</param>
/// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32")]
private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName);

/// <summary>
/// 读取INI文件中指定的Key的值
/// </summary>
/// <param name="lpAppName">节点名称。如果为null,则读取INI中所有节点名称,每个节点名称之间用\0分隔</param>
/// <param name="lpKeyName">Key名称。如果为null,则读取INI中指定节点中的所有KEY,每个KEY之间用\0分隔</param>
/// <param name="lpDefault">读取失败时的默认值</param>
/// <param name="lpReturnedString">读取的内容缓冲区,读取之后,多余的地方使用\0填充</param>
/// <param name="nSize">内容缓冲区的长度</param>
/// <param name="lpFileName">INI文件名</param>
/// <returns>实际读取到的长度</returns>
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName);

//另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符,会将\0及其后的字符截断,
//所以对于lpAppName或lpKeyName为null的情况就不适用
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName);

//再一种声明,使用string作为缓冲区的类型同char[]
[DllImport("kernel32")]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName);

/// <summary>
/// 将指定的键值对写到指定的节点,如果已经存在则替换。
/// </summary>
/// <param name="lpAppName">节点,如果不存在此节点,则创建此节点</param>
/// <param name="lpString">Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
/// <para>如果为string.Empty,则删除指定节点下的所有内容,保留节点</para>
/// <para>如果为null,则删除指定节点下的所有内容,并且删除该节点</para>
/// </param>
/// <param name="lpFileName">INI文件</param>
/// <returns>是否成功写入</returns>
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)] //可以没有此行
private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName);

/// <summary>
/// 将指定的键和值写到指定的节点,如果已经存在则替换
/// </summary>
/// <param name="lpAppName">节点名称</param>
/// <param name="lpKeyName">键名称。如果为null,则删除指定的节点及其所有的项目</param>
/// <param name="lpString">值内容。如果为null,则删除指定节点中指定的键。</param>
/// <param name="lpFileName">INI文件</param>
/// <returns>操作是否成功</returns>
[DllImport("kernel32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName);

#endregion

#region 方法封装
/// <summary>
/// 读取INI文件中指定INI文件中的所有节点名称(Section)
/// </summary>
/// <param name="iniFile">Ini文件路径</param>
/// <returns>所有节点,没有内容返回string[0]</returns>
public static string[] GetAllSectionNames(string iniFile)
{
uint MAX_BUFFER = 32767; //默认为32767

string[] sections = new string[0]; //返回值

//申请内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
if (bytesReturned != 0)
{
//读取指定内存的内容
string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString();

//每个节点之间用\0分隔,末尾有一个\0
sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}

//释放内存
Marshal.FreeCoTaskMem(pReturnedString);

return sections;
}

/// <summary>
/// 根据section取所有key、value。(乱码。。。。。。。)
/// </summary>
/// <param name="section">节点</param>
/// <param name="filePath">ini文件路径</param>
/// <returns>节点下所有“Key=Value”</returns>
public static string[] ReadSectionKeyValue(string section, string filePath)
{
UInt32 MAX_BUFFER = 32767;

string[] items = new string[0];

IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));

UInt32 bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, filePath);

if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0))
{
string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);

items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}

Marshal.FreeCoTaskMem(pReturnedString);

return items;
}

/// <summary>
/// 获取INI文件中指定节点(Section)中的所有条目的Key列表。
/// </summary>
/// <param name="iniFile">Ini文件路径</param>
/// <param name="section">节点名称</param>
/// <returns>节点列表,如果没有内容,反回string[0]</returns>
public static string[] GetAllItemKeys(string iniFile, string section)
{
string[] value = new string[0];
const int SIZE = 1024 * 10;

if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

char[] chars = new char[SIZE];
uint bytesReturned = GetPrivateProfileString(section, null, null, chars, SIZE, iniFile);

if (bytesReturned != 0)
{
value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
chars = null;

return value;
}

/// <summary>
/// 根据Section+Key取Value。
/// </summary>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <param name="filePath">ini文件路径</param>
/// <returns>Value</returns>
public static string ReadValueToKey(string section, string key, string filePath)
{
StringBuilder temp = new StringBuilder(500);
try
{
GetPrivateProfileString(section, key, "", temp, 500, filePath);
}
catch
{ }
return temp.ToString();
}

/// <summary>
/// 在INI文件中,将指定的键值对写到指定的节点,如果已经存在则替换。
///(会删除节点中其他的键,此节点只会有一个键值对)
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点,如果不存在此节点,则创建此节点</param>
/// <param name="items">键值对,多个用\0分隔,形如key1=value1\0key2=value2</param>
/// <returns>是否成功</returns>
public static bool WriteItems(string iniFile, string section, string items)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

if (string.IsNullOrEmpty(items))
{
throw new ArgumentException("必须指定键值对", "items");
}

return WritePrivateProfileSection(section, items, iniFile);
}

/// <summary>
/// 在INI文件中,指定节点写入指定的键及值。如果已经存在,则替换。如果没有则创建。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns>操作是否成功</returns>
public static bool WriteValue(string iniFile, string section, string key, string value)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
}

if (value == null)
{
throw new ArgumentException("值不能为null", "value");
}

return WritePrivateProfileString(section, key, value, iniFile);

}

/// <summary>
/// 在INI文件中,删除指定的节点。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <returns>操作是否成功</returns>
public static bool DeleteSection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

return WritePrivateProfileString(section, null, null, iniFile);
}

/// <summary>
/// 在INI文件中,删除指定节点中的所有内容。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <returns>操作是否成功</returns>
public static bool EmptySection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

return WritePrivateProfileSection(section, string.Empty, iniFile);
}

/// <summary>
/// 在INI文件中,删除指定节点中的指定的键。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <returns>操作是否成功</returns>
public static bool DeleteKey(string iniFile, string section, string key)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
}

if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
}

return WritePrivateProfileString(section, key, null, iniFile);
}
#endregion
}
}