前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >IniHelper——INI操作辅助类

IniHelper——INI操作辅助类

作者头像
用户1637609
发布2018-04-12 15:18:10
1.3K0
发布2018-04-12 15:18:10
举报
文章被收录于专栏:马洪彪马洪彪

使用INI配置文件,简单便捷。

该辅助工具类为C#操作INI文件的辅助类,源码在某位师傅的基础上完善的来,因为忘记最初的来源了,因此不能提及引用,在此深感遗憾,并对贡献者表示感谢。

代码语言:javascript
复制
  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Runtime.InteropServices;
  5 using System.Text;
  6 
  7 namespace Eyuan.Common
  8 {
  9     public static class INIHelper
 10     {
 11 
 12         #region 读写INI文件相关
 13         [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Ansi)]
 14         private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
 15 
 16         [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Ansi)]
 17         private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
 18 
 19         [DllImport("kernel32")]
 20         private static extern int GetPrivateProfileInt(string lpApplicationName, string lpKeyName, int nDefault, string lpFileName);
 21 
 22 
 23         [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Ansi)]
 24         private static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath);
 25 
 26         [DllImport("KERNEL32.DLL ", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Ansi)]
 27         private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath);
 28         #endregion
 29 
 30         #region 读写操作(字符串)
 31         /// <summary>
 32         /// 向INI写入数据
 33         /// </summary>
 34         /// <PARAM name="Section">节点名</PARAM>
 35         /// <PARAM name="Key">键名</PARAM>
 36         /// <PARAM name="Value">值(字符串)</PARAM>
 37         public static void Write(string Section, string Key, string Value, string path)
 38         {
 39             WritePrivateProfileString(Section, Key, Value, path);
 40         }
 41         /// <summary>
 42         /// 读取INI数据
 43         /// </summary>
 44         /// <PARAM name="Section">节点名</PARAM>
 45         /// <PARAM name="Key">键名</PARAM>
 46         /// <PARAM name="Path">值名</PARAM>
 47         /// <returns>值(字符串)</returns>
 48         public static string Read(string Section, string Key, string path)
 49         {
 50             StringBuilder temp = new StringBuilder(255);
 51             int i = GetPrivateProfileString(Section, Key, "", temp, 255, path);
 52             return temp.ToString();
 53         }
 54         #endregion
 55 
 56         #region 配置节信息
 57         /// <summary>
 58         /// 读取一个ini里面所有的节
 59         /// </summary>
 60         /// <param name="sections"></param>
 61         /// <param name="path"></param>
 62         /// <returns>-1:没有节信息,0:正常</returns>
 63         public static int GetAllSectionNames(out string[] sections, string path)
 64         {
 65             int MAX_BUFFER = 32767;
 66             IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
 67             int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
 68             if (bytesReturned == 0)
 69             {
 70                 sections = null;
 71                 return -1;
 72             }
 73             string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
 74             Marshal.FreeCoTaskMem(pReturnedString);
 75             //use of Substring below removes terminating null for split
 76             sections = local.Substring(0, local.Length - 1).Split('\0');
 77             return 0;
 78         }
 79         /// <summary>
 80         /// 返回指定配置文件下的节名称列表
 81         /// </summary>
 82         /// <param name="path"></param>
 83         /// <returns></returns>
 84         public static List<string> GetAllSectionNames(string path)
 85         {
 86             List<string> sectionList = new List<string>();
 87             int MAX_BUFFER = 32767;
 88             IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
 89             int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, path);
 90             if (bytesReturned != 0)
 91             {
 92                 string local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
 93                 Marshal.FreeCoTaskMem(pReturnedString);
 94                 sectionList.AddRange(local.Substring(0, local.Length - 1).Split('\0'));
 95             }
 96             return sectionList;
 97         }
 98 
 99         /// <summary>
100         /// 得到某个节点下面所有的key和value组合
101         /// </summary>
102         /// <param name="section">指定的节名称</param>
103         /// <param name="keys">Key数组</param>
104         /// <param name="values">Value数组</param>
105         /// <param name="path">INI文件路径</param>
106         /// <returns></returns>
107         public static int GetAllKeyValues(string section, out string[] keys, out string[] values, string path)
108         {
109             byte[] b = new byte[65535];//配置节下的所有信息
110             GetPrivateProfileSection(section, b, b.Length, path);
111             string s = System.Text.Encoding.Default.GetString(b);//配置信息
112             string[] tmp = s.Split((char)0);//Key\Value信息
113             List<string> result = new List<string>();
114             foreach (string r in tmp)
115             {
116                 if (r != string.Empty)
117                     result.Add(r);
118             }
119             keys = new string[result.Count];
120             values = new string[result.Count];
121             for (int i = 0; i < result.Count; i++)
122             {
123                 string[] item = result[i].Split(new char[] { '=' });//Key=Value格式的配置信息
124                 //Value字符串中含有=的处理,
125                 //一、Value加"",先对""处理
126                 //二、Key后续的都为Value
127                 if (item.Length > 2)
128                 {
129                     keys[i] = item[0].Trim();
130                     values[i] = result[i].Substring(keys[i].Length + 1);
131                 }
132                 if (item.Length == 2)//Key=Value
133                 {
134                     keys[i] = item[0].Trim();
135                     values[i] = item[1].Trim();
136                 }
137                 else if (item.Length == 1)//Key=
138                 {
139                     keys[i] = item[0].Trim();
140                     values[i] = "";
141                 }
142                 else if (item.Length == 0)
143                 {
144                     keys[i] = "";
145                     values[i] = "";
146                 }
147             }
148             return 0;
149         }
150         /// <summary>
151         /// 得到某个节点下面所有的key
152         /// </summary>
153         /// <param name="section">指定的节名称</param>
154         /// <param name="keys">Key数组</param>
155         /// <param name="path">INI文件路径</param>
156         /// <returns></returns>
157         public static int GetAllKeys(string section, out string[] keys, string path)
158         {
159             byte[] b = new byte[65535];
160 
161             GetPrivateProfileSection(section, b, b.Length, path);
162             string s = System.Text.Encoding.Default.GetString(b);
163             string[] tmp = s.Split((char)0);
164             ArrayList result = new ArrayList();
165             foreach (string r in tmp)
166             {
167                 if (r != string.Empty)
168                     result.Add(r);
169             }
170             keys = new string[result.Count];
171             for (int i = 0; i < result.Count; i++)
172             {
173                 string[] item = result[i].ToString().Split(new char[] { '=' });
174                 if (item.Length == 2)
175                 {
176                     keys[i] = item[0].Trim();
177                 }
178                 else if (item.Length == 1)
179                 {
180                     keys[i] = item[0].Trim();
181                 }
182                 else if (item.Length == 0)
183                 {
184                     keys[i] = "";
185                 }
186             }
187             return 0;
188         }
189         /// <summary>
190         /// 获取指定节下的Key列表
191         /// </summary>
192         /// <param name="section">指定的节名称</param>
193         /// <param name="path">配置文件名称</param>
194         /// <returns>Key列表</returns>
195         public static List<string> GetAllKeys(string section, string path)
196         {
197             List<string> keyList = new List<string>();
198             byte[] b = new byte[65535];
199             GetPrivateProfileSection(section, b, b.Length, path);
200             string s = System.Text.Encoding.Default.GetString(b);
201             string[] tmp = s.Split((char)0);
202             List<string> result = new List<string>();
203             foreach (string r in tmp)
204             {
205                 if (r != string.Empty)
206                     result.Add(r);
207             }
208             for (int i = 0; i < result.Count; i++)
209             {
210                 string[] item = result[i].Split(new char[] { '=' });
211                 if (item.Length == 2 || item.Length == 1)
212                 {
213                     keyList.Add(item[0].Trim());
214                 }
215                 else if (item.Length == 0)
216                 {
217                     keyList.Add(string.Empty);
218                 }
219             }
220             return keyList;
221         }
222         /// <summary>
223         /// 获取值
224         /// </summary>
225         /// <param name="section"></param>
226         /// <param name="path"></param>
227         /// <returns></returns>
228         public static List<string> GetAllValues(string section, string path)
229         {
230             List<string> keyList = new List<string>();
231             byte[] b = new byte[65535];
232             GetPrivateProfileSection(section, b, b.Length, path);
233             string s = System.Text.Encoding.Default.GetString(b);
234             string[] tmp = s.Split((char)0);
235             List<string> result = new List<string>();
236             foreach (string r in tmp)
237             {
238                 if (r != string.Empty)
239                     result.Add(r);
240             }
241             for (int i = 0; i < result.Count; i++)
242             {
243                 string[] item = result[i].Split(new char[] { '=' });
244                 if (item.Length == 2 || item.Length == 1)
245                 {
246                     keyList.Add(item[1].Trim());
247                 }
248                 else if (item.Length == 0)
249                 {
250                     keyList.Add(string.Empty);
251                 }
252             }
253             return keyList;
254         }
255        
256         #endregion
257 
258         #region 通过值查找键(一个节中的键唯一,可能存在多个键值相同,因此反查的结果可能为多个)
259 
260         /// <summary>
261         /// 第一个键
262         /// </summary>
263         /// <param name="section"></param>
264         /// <param name="path"></param>
265         /// <param name="value"></param>
266         /// <returns></returns>
267         public static string GetFirstKeyByValue(string section, string path, string value)
268         {
269             foreach (string key in GetAllKeys(section, path))
270             {
271                 if (ReadString(section, key, "", path) == value)
272                 {
273                     return key;
274                 }
275             }
276             return string.Empty;
277         }
278         /// <summary>
279         /// 所有键
280         /// </summary>
281         /// <param name="section"></param>
282         /// <param name="path"></param>
283         /// <param name="value"></param>
284         /// <returns></returns>
285         public static List<string> GetKeysByValue(string section, string path, string value)
286         {
287             List<string > keys = new List<string>();
288             foreach (string key in GetAllKeys(section, path))
289             {
290                 if (ReadString(section, key, "", path) == value)
291                 {
292                     keys.Add(key);
293                 }
294             }
295             return keys;
296         }
297         #endregion
298 
299 
300         #region 具体类型的读写
301 
302         #region string
303         /// <summary>
304         /// 
305         /// </summary>
306         /// <param name="sectionName"></param>
307         /// <param name="keyName"></param>
308         /// <param name="defaultValue" />
309         /// <param name="path"></param>
310         /// <returns></returns>
311         public static string ReadString(string sectionName, string keyName, string defaultValue, string path)
312         {
313             const int MAXSIZE = 255;
314             StringBuilder temp = new StringBuilder(MAXSIZE);
315             GetPrivateProfileString(sectionName, keyName, defaultValue, temp, 255, path);
316             return temp.ToString();
317         }
318 
319         /// <summary>
320         /// 
321         /// </summary>
322         /// <param name="sectionName"></param>
323         /// <param name="keyName"></param>
324         /// <param name="value"></param>
325         /// <param name="path"></param>
326         public static void WriteString(string sectionName, string keyName, string value, string path)
327         {
328             WritePrivateProfileString(sectionName, keyName, value, path);
329         }
330         #endregion
331 
332         #region Int
333         /// <summary>
334         /// 
335         /// </summary>
336         /// <param name="sectionName"></param>
337         /// <param name="keyName"></param>
338         /// <param name="defaultValue"></param>
339         /// <param name="path"></param>
340         /// <returns></returns>
341         public static int ReadInteger(string sectionName, string keyName, int defaultValue, string path)
342         {
343 
344             return GetPrivateProfileInt(sectionName, keyName, defaultValue, path);
345 
346         }
347         /// <summary>
348         /// 
349         /// </summary>
350         /// <param name="sectionName"></param>
351         /// <param name="keyName"></param>
352         /// <param name="value"></param>
353         /// <param name="path"></param>
354         public static void WriteInteger(string sectionName, string keyName, int value, string path)
355         {
356 
357             WritePrivateProfileString(sectionName, keyName, value.ToString(), path);
358 
359         }
360         #endregion
361 
362         #region bool
363         /// <summary>
364         /// 读取布尔值
365         /// </summary>
366         /// <param name="sectionName"></param>
367         /// <param name="keyName"></param>
368         /// <param name="defaultValue"></param>
369         /// <param name="path"></param>
370         /// <returns></returns>
371         public static bool ReadBoolean(string sectionName, string keyName, bool defaultValue, string path)
372         {
373 
374             int temp = defaultValue ? 1 : 0;
375 
376             int result = GetPrivateProfileInt(sectionName, keyName, temp, path);
377 
378             return (result == 0 ? false : true);
379 
380         }
381         /// <summary>
382         /// 写入布尔值
383         /// </summary>
384         /// <param name="sectionName"></param>
385         /// <param name="keyName"></param>
386         /// <param name="value"></param>
387         /// <param name="path"></param>
388         public static void WriteBoolean(string sectionName, string keyName, bool value, string path)
389         {
390             string temp = value ? "1 " : "0 ";
391             WritePrivateProfileString(sectionName, keyName, temp, path);
392         }
393         #endregion
394 
395         #endregion
396 
397         #region 删除操作
398         /// <summary>
399         /// 删除指定项
400         /// </summary>
401         /// <param name="sectionName"></param>
402         /// <param name="keyName"></param>
403         /// <param name="path"></param>
404         public static void DeleteKey(string sectionName, string keyName, string path)
405         {
406             WritePrivateProfileString(sectionName, keyName, null, path);
407         }
408 
409         /// <summary>
410         /// 删除指定节下的所有项
411         /// </summary>
412         /// <param name="sectionName"></param>
413         /// <param name="path"></param>
414         public static void EraseSection(string sectionName, string path)
415         {
416             WritePrivateProfileString(sectionName, null, null, path);
417         }
418         #endregion
419 
420         #region 判断节、键是否存在
421         /// <summary>
422         /// 指定节知否存在
423         /// </summary>
424         /// <param name="section"></param>
425         /// <param name="fileName"></param>
426         /// <returns></returns>
427         public static bool ExistSection(string section, string fileName)
428         {
429             string[] sections = null;
430             GetAllSectionNames(out sections, fileName);
431             if (sections != null)
432             {
433                 foreach (var s in sections)
434                 {
435                     if (s == section)
436                     {
437                         return true;
438                     }
439                 }
440             }
441             return false;
442         }
443         /// <summary>
444         /// 指定节下的键是否存在
445         /// </summary>
446         /// <param name="section"></param>
447         /// <param name="key"></param>
448         /// <param name="fileName"></param>
449         /// <returns></returns>
450         public static bool ExistKey(string section, string key, string fileName)
451         {
452             string[] keys = null;
453             GetAllKeys(section, out keys, fileName);
454             if (keys != null)
455             {
456                 foreach (var s in keys)
457                 {
458                     if (s == key)
459                     {
460                         return true;
461                     }
462                 }
463             }
464             return false;
465         }
466         #endregion
467 
468         #region 同一Section下添加多个Key\Value
469         /// <summary>
470         /// 
471         /// </summary>
472         /// <param name="section"></param>
473         /// <param name="keyList"></param>
474         /// <param name="valueList"></param>
475         /// <param name="path"></param>
476         /// <returns></returns>
477         public static bool AddSectionWithKeyValues(string section, List<string> keyList, List<string> valueList, string path)
478         {
479             bool bRst = true;
480             //判断Section是否已经存在,如果存在,返回false
481             //已经存在,则更新
482             //if (GetAllSectionNames(path).Contains(section))
483             //{
484             //    return false;
485             //}
486             //判断keyList中是否有相同的Key,如果有,返回false
487 
488             //添加配置信息
489             for (int i = 0; i < keyList.Count; i++)
490             {
491                 WriteString(section, keyList[i], valueList[i], path);
492             }
493             return bRst;
494         }
495         #endregion
496     }
497 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2014-05-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档