C#操作INI文件(我的处女作啊)

  1// 目的: 存储与读取*.ini文件(函数)
  2//        存储和读取非值以及字符串,存储/读取非值:WriteIniTF/GetIniTF
  3//        存储/读取字符串:WriteIniStr/GetIniStr'
  4// 输入: 指定节点名,指定主键
  5//        WriteIniTF/GetIniTF:    节点名、主键、键值/(省略)、文件名
  6//        WriteIniStr/GetIniStr:  节点名、主键、键值/(省略)、文件名
  7//        AppName: 节点名(默认为Setting)
  8//        AppPath: 路径名
  9//        In_Key:  键名(标示)
 10//        NodeName:键值(输入的数据)
 11// 返回: 返回指定节点名主键的键值
 12//########################################################################
 13
 14using System;
 15using System.Collections.Generic;
 16using System.Text;
 17using System.Runtime.InteropServices;
 18using System.IO;
 19using System.Windows.Forms;
 20using System.Collections.Specialized;//stringCollection要用到嘀
 21
 22namespace SoIniEdit
 23{
 24
 25    /// <summary>
 26    /// 
 27    /// </summary>

 28    public class ControlIni
 29    {
 30
 31        //引用API
 32        [DllImport("kernel32")]
 33        private static extern long WritePrivateProfileString(string section, string key, string     val, string filePath);
 34        [DllImport("kernel32")]
 35        private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath);
 36        [DllImport("kernel32")]
 37        private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);
 38        //[DllImport("kernel32")]
 39        //private static extern int GetPrivateProfileSection(string section, string key, int size, string filePath);
 40        [DllImport("kernel32")]
 41        private static extern int GetPrivatePfileInt(string section, string key, int val, string filePath);
 42
 43 
 44
 45        [DllImport("kernel32")]
 46        private static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize,
 47        string lpFileName); 
 48
 49        private  static string strSub;                          //程序过程函数名
 50        private static string strCls = "ControlIni";        //代码文件名
 51        private static string strErrs;                          //运行说明  
 52        private string strTitle;                                  //弹出标题
 53        private string strDate;                                 //初始化时间
 54
 55        
 56    /// <summary>
 57    /// 定义构造函数
 58    /// </summary>

 59        public ControlIni()
 60        {
 61      
 62            bZiError = GetIniTF("setting""bType1""Setting\\SoErrors", RootType.nRootDefalut);
 63            bSystemError = GetIniTF("setting""bType2""Setting\\SoErrors", RootType.nRootDefalut);
 64            bSystemMsg = GetIniTF("setting""bType3""Setting\\SoErrors", RootType.nRootDefalut);
 65            bSystemJingGao = GetIniTF("setting""bType4""Setting\\SoErrors", RootType.nRootDefalut);
 66            strDate = GetIniStr("Set""date""LogInfos\\ErrLog", RootType.nRootDefalut);
 67         }

 68        private static string AppPath;   //路径名
 69        private static string AppName;   //节点名
 70
 71
 72       private bool bZiError = false;           //是否弹出错误提示框(默认不弹出) 
 73       private bool bSystemError = false;       //是否弹出错误提示框(默认不弹出)
 74       private bool bSystemMsg = false;         //是否弹出错误提示框(默认不弹出)
 75       private bool bSystemJingGao = false;     //是否弹出错误提示框(默认不弹出)
 76
 77    
 78
 79        /// <summary>
 80        /// 提示错误类型
 81        /// </summary>

 82      private   enum  ShowMessageType
 83        {
 84          /// <summary>
 85            /// tpye1:自定义错误
 86          /// </summary>

 87            type1=1,
 88          /// <summary>
 89            /// tpye2:系统错误
 90          /// </summary>

 91            type2=2,
 92          /// <summary>
 93            /// type3:系统提示
 94          /// </summary>

 95            type3=3,
 96          /// <summary>
 97            /// type4:系统警告
 98          /// </summary>

 99            type4=4
100        }

101
102        /// <summary>
103        /// 用户选择INI文件的类型 0为系统默认路径 1为选择路径 aaa
104        /// </summary>

105        public enum RootType
106        {
107            /// <summary>
108            ///  nRootDefalut:系统默认路径
109            /// </summary>

110            nRootDefalut = 0,
111            /// <summary>
112            ///nRootUser :用户选择路径
113            /// </summary>

114            nRootUser = 1
115        }

116        //
117        /// <summary>
118        ///  获取路径   当nRoot为0 时表示系统路径、1表示用户传入ini文件完整路径  下面函数中nRoot同样的意思
119        /// </summary>
120        /// <param name="PathName">路径名</param>
121        /// <param name="nRoot">选择方式 nRootDefalut 表法系统默认路径</param>
122        /// <returns></returns>

123        public String GetPath(string PathName, RootType nRoot)
124        {
125    
126            try
127            {  
128                strSub = "GetPath";
129               //按输入条件重构INI文件路径
130               
131                if (nRoot == 0)
132                {
133                    //程序根目录路径   
134                    AppPath = Directory.GetCurrentDirectory() + "\\" + PathName + ".ini";
135                }

136           else 
137                {
138                    //自定义路径 
139                    AppPath = PathName;
140                }

141                return AppPath;
142            }

143
144            catch (Exception Err)
145            {
146                strErrs = Err.Message;
147                strErrs = "获取路径失败!";
148                SubError("""", PathName, strErrs, ShowMessageType.type1,RootType.nRootDefalut  );
149                return Err.Message;     //返回异常消息
150            }

151            finally
152            {
153                //程序运行日志
154                SubLog(strSub);
155            }

156       }

157
158        //*******************************************************
159        //
160        //*******************************************************
161        /// <summary>
162        /// 得到ini文件路径名 
163        /// </summary>
164       /// <param name="PathName">路径名</param>
165        /// <returns></returns>

166       public  String GetPath(string PathName)
167        {
168            strSub = "GetPath2";
169            //默认加载为系统根目录路径
170            int nRoot = 0;
171            if (nRoot == 0)
172            {
173                //程序根目录路径   
174                AppPath = Directory.GetCurrentDirectory() + "\\" + PathName + ".ini";
175            }

176            else
177            {
178                //GetPath("",
179                   
180                //自定义路径 
181                AppPath = PathName;
182            }

183            return AppPath;
184        }

185
186        //
187        /// <summary>
188        ///  获取节点
189        /// </summary>
190        /// <param name="NodeName"></param>
191        /// <returns></returns>

192        private  string Node(string NodeName)
193        {
194            try
195            {
196                strSub = "Node";
197                if (NodeName == null)
198                {
199                    AppName = "Setting"//如果节点名为空,设置为默认 Setting
200                }

201                else
202                {
203                    AppName = NodeName; //获得节点名称
204                }

205                return AppName;
206            }

207            catch(Exception e)
208            {
209               strErrs = "读取Bool型键值失败!";
210               SubError(NodeName, """", strErrs, ShowMessageType.type1, RootType.nRootDefalut);
211               return  e.Message;
212            }

213            finally
214            {  
215                //程序运行日志
216                SubLog(strSub);
217               
218            }

219        }

220         //====================================函数===========================================
221        //目的: 存储/读取非值
222        //假设: Setting: 节点名; AppPath: 路径
223        //输入:
224            // AppName: 节点名
225            //  In_Key:  主键
226            //  In_Data: 键值
227            //  AppPath: 路径名
228        // 返回:    False/True
229        //===============================================================================
230        //
231        /// <summary>
232        /// 读取Bool 型
233        /// </summary>
234        /// <param name="NodeName">节点名</param>
235        /// <param name="In_Key">主键</param>
236        /// <param name="PathName">路径名</param>
237        /// <param name="nRoot">选择INI方式</param>
238        /// <returns></returns>

239        public bool  GetIniTF(string NodeName, string In_Key, string PathName, RootType nRoot)
240        {
241            
242            strSub = "GetIniTF";
243            try
244            {
245                GetPath(PathName, nRoot); //获取路径 
246                Node(NodeName);           //获取节点
247                StringBuilder temp = new StringBuilder(255);
248                //调用API,获取节点值
249                GetPrivateProfileString(NodeName, In_Key, "", temp, 255, AppPath);
250                if (temp.ToString() == "1"return true;    //如果是1返回true
251                else   return false;   // if (temp.ToString() == "0")
252            }

253            catch
254            {
255                strErrs = "读取Bool型键值失败!";
256                SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut); //调用异常函数
257                return false ;
258
259            }

260            finally
261            {
262                //程序运行日志
263                SubLog(strSub);
264            }

265       }

266
267        //
268        /// <summary>
269        ///  写入Bool型
270        /// </summary>
271        /// <param name="NodeName"></param>
272        /// <param name="In_Key"></param>
273        /// <param name="In_Data"></param>
274        /// <param name="PathName"></param>
275        /// <param name="nRoot"></param>
276        /// <returns></returns>

277        public int WriteIniTF(string NodeName, string In_Key, bool In_Data, string PathName, RootType nRoot)
278        {
279            strSub = "WriteIniTF";
280            try
281            {   
282                GetPath(PathName, nRoot);//获取路径 
283                Node(NodeName);          //获取节点
284
285                if (In_Data == true)  //如果键值为真 写入1
286                {   
287                    //调用API,根据键值类型写入值
288                    WritePrivateProfileString(NodeName, In_Key, "1", AppPath);
289                    return 1;
290                }

291                else                 //如果键值为假 写入0
292                {
293                    //调用API,根据键值类型写入值
294                    WritePrivateProfileString(NodeName, In_Key, "0", AppPath);
295                    return -1;
296                }

297            }

298            catch
299            {
300                strErrs = "写入Bool型键值失败!";
301                SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut);
302                return -1;
303            }

304            finally
305            {
306                //程序运行日志
307                SubLog(strSub);
308            }

309         }

310         //====================================函数===================================
311         //目的: 存储/读取字符串值
312         //假设: AppName: 节点名; AppPath: 路径(可以为空)
313         //输入:
314         //       AppName: 节点名
315         //       In_Key:  主键
316         //       In_Data: 键值
317         //       AppPath: 路径名
318         //返回:指定节点的主键键值
319         //==================================================================================
320         //
321        /// <summary>
322        ///  读取字符型
323        /// </summary>
324        /// <param name="NodeName"></param>
325        /// <param name="In_Key"></param>
326        /// <param name="PathName"></param>
327        /// <param name="nRoot"></param>
328        /// <returns></returns>

329        public string GetIniStr(string NodeName, string In_Key, string PathName, RootType nRoot)
330         {
331             strSub = "GetIniStr";
332             try
333             {
334                 GetPath(PathName, nRoot);//获取路径 
335                 Node(NodeName);          //获取节点
336                 StringBuilder temp = new StringBuilder(255);
337
338                 //如果节点、键名 、路径为空,返回       
339                 if ((NodeName == null|| (In_Key == null|| (PathName == null))
340                 {
341                     return null;
342                 }

343
344                 //调用API,获取字符型键值
345                 int i = GetPrivateProfileString(NodeName, In_Key, "", temp, 255, AppPath);
346                 return temp.ToString();
347             }

348
349             catch  (Exception e)
350             {
351                strErrs = "读取字符型键值失败!";
352                SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut);
353                return  e.Message;
354             }

355
356             finally
357             {
358                 //程序运行日志
359                 SubLog(strSub);
360             }

361         }

362
363
364         //
365        /// <summary>
366        ///  写入字符型
367        /// </summary>
368        /// <param name="NodeName"></param>
369        /// <param name="In_Key"></param>
370        /// <param name="In_Data"></param>
371        /// <param name="PathName"></param>
372        /// <param name="nRoot"></param>
373        /// <returns></returns>

374        public int  WriteIniStr(string NodeName, string In_Key, string In_Data, string PathName, RootType nRoot)
375         {
376             strSub = "WriteIniStr";
377             try
378             {
379                 GetPath(PathName, nRoot);//获取路径 
380                 Node(NodeName);          //获取节点
381                 //如果节点、键名、路径为空,返回 
382                 if ((NodeName == null|| (In_Key == null|| (PathName == null))  
383                 {
384                     return -1;
385                 }

386                 else
387                 {
388                     //调用API写入字符型键值
389                     WritePrivateProfileString(NodeName, In_Key, In_Data, AppPath);
390                     return 1;
391                 }

392             }

393             catch
394             {
395                 strErrs = "写入字符型键值失败!";
396                 SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut);
397                 return -1;
398             }

399             finally
400             {
401                 //程序运行日志
402                 SubLog(strSub);
403             }

404         }

405
406         //
407        /// <summary>
408        /// 删除指定键名
409        /// </summary>
410        /// <param name="NodeName"></param>
411        /// <param name="In_Key"></param>
412        /// <param name="PathName"></param>
413        /// <param name="nRoot"></param>
414        /// <returns></returns>

415        public int  DelKey(string NodeName, string In_Key, string PathName, RootType nRoot)
416         {
417             strSub = "DelKey";
418             try
419             {
420                 GetPath(PathName, nRoot); //获取路径 
421                 Node(NodeName);           //获取节点
422                 //如果节点、键 、路径为空,返回
423                 WritePrivateProfileString(AppName, In_Key, null , AppPath);
424                // SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut);
425                 return 1;
426             }

427             catch
428             {
429                 strErrs = "删除指定键名失败!";
430                 SubError(NodeName, In_Key, PathName, strErrs, ShowMessageType.type1, RootType.nRootDefalut);
431                 return -1;
432             }

433             finally
434             {
435                 //程序运行日志
436                 SubLog(strSub );
437             }

438         }

439        /// <summary>
440        /// 删除节点
441        /// </summary>
442        /// <param name="NodeName"></param>
443        /// <param name="PathName"></param>
444        /// <param name="nRoot"></param>
445        /// <returns></returns>

446        public int DelNode(string NodeName, string PathName, RootType nRoot)
447        {
448            
449            strSub = "DelNode";
450            try
451            {
452                GetPath(PathName, nRoot); //获取路径 
453                Node(NodeName);           //获取节点
454                WritePrivateProfileString(AppName,null , null , AppPath);
455                return 1;
456            }

457            catch
458            {
459                strErrs = "删除指定节点失败!";
460                SubError(NodeName, """", strErrs, ShowMessageType.type1,nRoot );
461                return -1;
462            }

463            finally
464            
465                 //程序运行日志
466                SubLog(strSub);
467            }

468        }

469
470
471//        '===================================================================================
472//Public Function KeyNum(NodeName As String, PathName As String) As Long
473//'获取指定节点下的所有键
474//On Error GoTo KeyNumErr
475//  Dim ss As String
476//  Dim pos As Integer, Count As Integer
477//  Dim Key() As String
478//  Dim buffer As String
479  
480//  Call Path(PathName)
481//  Call Node(NodeName)
482  
483//  buffer = String(32767, 0)
484//  GetPrivateProfileSection AppName, buffer, Len(buffer), AppPath
485
486/// <summary>
487/// 
488/// </summary>
489/// <param name="nodeName"></param>
490/// <param name="PathName"></param>
491/// <returns></returns>

492        public int  KeyNum(string nodeName, string PathName)
493        {
494          //  string ss;
495            //long a;
496            StringCollection items = new StringCollection(); 
497            
498            //int count;
499            //StringBuilder buffer = new StringBuilder(255);
500            //string buffer = new string(char(0), 0);
501            byte[] buffer = new byte[32768];
502            int bufLen = 0;
503            int a=0;
504            bufLen = GetPrivateProfileSection(nodeName, buffer, buffer.GetUpperBound(0), PathName);
505
506
507            if (bufLen > 0)
508            {
509                StringBuilder sb = new StringBuilder();
510                for (int i = 0; i < bufLen; i++)
511                {
512                    //if (buffer[i] != 0)
513                    //{
514                    //    sb.Append((char)buffer[i]);
515                    //}
516                    //else
517                    //{
518                    //    if (sb.Length > 0)
519                    //    {
520                    //        items.Add(sb.ToString());
521                    //        sb = new StringBuilder();
522                    //    }
523                    //}
524
525
526                    if (buffer[i]==61)
527                    {
528                        a++;
529                    }

530                   
531
532                }

533            }

534          return a;
535            //   return items.Count;
536         
537
538
539           // return bufLen;
540
541        }

542
543 
544
545        /// <summary>
546        /// 自定义错误函数
547        /// </summary>
548        /// <param name="NodeName">节点名</param>
549        /// <param name="In_Key">键值</param>
550        /// <param name="PathName">路径名</param>
551        /// <param name="strErrs">错误信息</param>
552        /// <param name="nType">弹出错误类型</param>
553        /// <param name="nRootType">选择文件目录类型</param>
554        /// <returns></returns>

555        private  int SubError(string NodeName, string In_Key, string PathName, string strErrs, ShowMessageType nType,RootType nRootType)
556        {
557            String strErr;
558            strErr = strErrs + "([" + NodeName + "][" + In_Key + "][" + PathName + "].)"+strCls ;
559            
560            bool bShow ;
561            string strNode;
562            string strKey;
563            switch( nType )
564            {
565                case ShowMessageType .type1 :
566                    strTitle = "错误";
567                    bShow = bZiError;
568                    break;
569                case ShowMessageType.type2:
570                    strTitle = "错误";
571                    bShow = bSystemError;
572                    break;
573                case ShowMessageType.type3:
574                    strTitle = "提示";
575                    bShow = bSystemMsg;
576                    break;
577                case ShowMessageType.type4:
578                    strTitle = "警告";
579                    bShow = bSystemJingGao;
580                    break;
581                default:
582                    bShow = false ;
583                    break;
584                
585
586            }

587            if (bShow == true)
588            {
589                MessageBox.Show(strErr, strTitle);
590              
591            }

592
593            DateTime tNow = DateTime.Now;                                 //得到系统时间
594            DateTime dKey = Convert.ToDateTime(strDate);                  //将键值转换为时间
595            TimeSpan dCompare = tNow.Subtract(dKey);                      //将当前时间与键值时间比较
596            strNode = tNow.Year + "-" + tNow.Month + "-" + tNow.Day;      //得到系统时间的年月日
597            strKey = tNow.Hour + ":" + tNow.Minute + ":" + tNow.Second;   //得到系统时间的时分秒
598            WriteIniStr(strNode, strKey , strErr, "LogInfos\\ErrLog", RootType.nRootDefalut);
599            int i =Convert .ToInt32 ( GetIniStr("Set""Days""LogInfos\\ErrLog", RootType.nRootDefalut));
600            if (dCompare.Days > i)                                        //若当前时间与键值时间比较大于指定时间 
601            {
602               //将当前时间设为比较值
603               WriteIniStr("Set""date", strNode, "LogInfos\\ErrLog", RootType.nRootDefalut);
604               //删除大于时间段的键
605               DelNode(strDate, "LogInfos\\ErrLog", RootType.nRootDefalut); 
606            }

607            //程序运行异常日志
608            SubErrLog(strSub );
609            return 1;
610        }

611        //记录系统日志
612        private  void SubLog(string strSubName)
613        {
614            //调用外部接口函数写函数运行过程详细情况(预留)
615        }

616
617        private  void SubErrLog(string strSubName)
618        {
619            //写函数运行过程异常详细情况(预留)
620
621        }

622    }

623}

624
625
626
627/////////////////////////////////////////////////////////////////////////////////
628//测试窗体
629
630/////////////////////////////////////////////////////////////////////////////////
631
632
633using System;
634using System.Collections.Generic;
635using System.ComponentModel;
636using System.Data;
637using System.Drawing;
638using System.Text;
639using System.Windows.Forms;
640
641namespace Ini
642{
643    public partial class Form1 : Form
644    {
645        SoIniEdit.ControlIni s = new SoIniEdit.ControlIni();
646
647        public Form1()
648        {
649            InitializeComponent();
650        }

651
652        private void button1_Click(object sender, EventArgs e)
653        {
654            MessageBox.Show(s.GetPath("open"0));
655            //MessageBox.Show(s.GetPath(@"E:\open.ini", 1));
656                MessageBox.Show(s.GetPath(@"E:\open.ini", SoIniEdit.ControlIni.RootType.nRootUser));
657            
658        }

659
660        private void button2_Click(object sender, EventArgs e)
661        {
662            this.textBox1.Text = s.GetIniStr("a""b""open",0);
663           // this.textBox1.Text = s.GetIniStr("", "", "", 0);
664        }

665
666        private void button3_Click(object sender, EventArgs e)
667        {
668         this.textBox2.Text=   s.WriteIniStr("aa""bb""cc""open"0).ToString ();
669         //this.textBox3.Text = s.WriteIniStr("aa", "bb", "cc", @"E:\open.ini", 1).ToString();
670         this.textBox3.Text = s.WriteIniStr("aa""bb""cc"@"E:\open.ini", SoIniEdit.ControlIni.RootType.nRootUser).ToString ();
671        }

672
673        private void button4_Click(object sender, EventArgs e)
674        {
675           
676        }

677
678        private void button5_Click(object sender, EventArgs e)
679        {
680            this.textBox4 .Text = s.DelKey("qq""aa""open"0).ToString ();
681            //s.DelKey("as", "aa", "sa", 0);
682        }

683
684        private void button6_Click(object sender, EventArgs e)
685        {
686            this.textBox5.Text = s.GetIniTF("qq""aa""open"0).ToString();
687        }

688
689        private void button7_Click(object sender, EventArgs e)
690        {
691            //this.textBox6.Text = s.WriteIniTF("aa", "bb", false  , "open", 0).ToString ();
692            this.textBox6.Text = s.WriteIniTF("aa""bb"true , "open"0).ToString ();
693        }

694
695        private void button4_Click_1(object sender, EventArgs e)
696        {
697            s.DelNode("aaa""open"0);
698        }

699
700        private void button8_Click(object sender, EventArgs e)
701        {
702       
703        }

704    }

705}

706
707
708
709
710
711
712 
713
原文地址:https://www.cnblogs.com/lhjhl/p/1242267.html