INI文件管理类代码

  1using System;
  2using System.IO;
  3using System.Data;
  4using System.Runtime.InteropServices;
  5using System.Text;
  6using System.Collections;
  7using System.Collections.Specialized;
  8
  9namespace FaibClass.IniFile
 10{
 11    /// <summary>
 12    /// INI配置文件管理库,
 13    /// Design By Faib Studio.
 14    /// </summary>

 15    public class IniFile
 16    {
 17    
 18        internal static string _FileName;
 19        private SectionCollection _Sections=new SectionCollection();
 20
 21        /// <summary>
 22        /// 构造类。
 23        /// </summary>

 24        public IniFile()
 25        {
 26        }

 27
 28        /// <summary>
 29        /// INI文件名。
 30        /// </summary>

 31        public string FileName
 32        {
 33            get{return _FileName;}
 34            set{_FileName=value;this.LoadDataStructure();}
 35        }

 36
 37        /// <summary>
 38        /// 构造类,传入文件名。
 39        /// </summary>
 40        /// <param name="FileName">INI文件名。</param>

 41        public IniFile(string FileName)
 42        {
 43            _FileName=FileName;
 44            LoadDataStructure();
 45        }

 46
 47        /// <summary>
 48        /// 返回版权信息。
 49        /// </summary>

 50        public string CopyrightMessage
 51        {
 52            get{return "Copyright (C) 2006 Faib Studio All Rights Reserved";}
 53        }

 54
 55        /// <summary>
 56        /// 读取键值。
 57        /// </summary>
 58        /// <param name="Section">节名称。</param>
 59        /// <param name="Key">键名称</param>
 60        /// <returns>键值。</returns>

 61        public string ReadValue(string Section,string Key)
 62        {
 63            if(_FileName==null || _FileName=="")return null;
 64            return IniFile.ReadValue(_FileName,Section,Key);
 65        }

 66
 67        /// <summary>
 68        /// 读取键值。
 69        /// </summary>
 70        /// <param name="FileName">文件路径。</param>
 71        /// <param name="Section">节名称。</param>
 72        /// <param name="Key">键名称</param>
 73        /// <returns>键值。</returns>

 74        public static string ReadValue(string FileName,string Section,string Key)
 75        {
 76            byte[] temp=new byte[255];
 77            try
 78            {
 79                int l = WindowsAPI.GetPrivateProfileString(Section,Key,"",temp, temp.GetUpperBound(0) ,FileName);
 80                string ret = Encoding.GetEncoding(0).GetString(temp);
 81                return ret.Substring(0,ret.IndexOf((char)0));
 82            }

 83            catch
 84            {
 85                throw;
 86            }

 87        }

 88
 89        /// <summary>
 90        /// 写入键值。
 91        /// </summary>
 92        /// <param name="Section">节名称。</param>
 93        /// <param name="Key">键名称。</param>
 94        /// <param name="Value">键值。</param>

 95        public void WriteValue(string Section,string Key,object Value)
 96        {
 97            if(_FileName==null || _FileName=="")return;
 98            IniFile.WriteValue(_FileName,Section,Key,Value);
 99            this.LoadDataStructure();
100        }

101
102        /// <summary>
103        /// 写入键值。
104        /// </summary>
105        /// <param name="FileName">文件路径。</param>
106        /// <param name="Section">节名称。</param>
107        /// <param name="Key">键名称。</param>
108        /// <param name="Value">键值。</param>

109        public static void WriteValue(string FileName,string Section,string Key,object Value)
110        {
111            WindowsAPI.WritePrivateProfileString(Section,Key,Value.ToString(),FileName);
112        }

113
114        /// <summary>
115        /// 移除节。
116        /// </summary>
117        /// <param name="Section">节名称。</param></param>

118        public void RemoveSection(string Section)
119        {
120            if(_FileName==null || _FileName=="")return;
121            IniFile.RemoveSection(_FileName,Section);
122            this.LoadDataStructure();
123        }

124
125        /// <summary>
126        /// 移除节。
127        /// </summary>
128        /// <param name="FileName">文件路径。</param>
129        /// <param name="Section">节名称。</param>

130        public static void RemoveSection(string FileName,string Section)
131        {
132            WindowsAPI.WritePrivateProfileString(Section, nullnull, FileName);
133        }

134
135        /// <summary>
136        /// 移除键值。
137        /// </summary>
138        /// <param name="Section">节名称。</param>
139        /// <param name="Key">键名称。</param>

140        public void RemoveKey(string Section,string Key)
141        {
142            if(_FileName==null || _FileName=="")return;
143            IniFile.RemoveKey(_FileName,Section,Key);
144            this.LoadDataStructure();
145        }

146
147        /// <summary>
148        /// 移除键值。
149        /// </summary>
150        /// <param name="FileName">文件路径。</param>
151        /// <param name="Section">节名称。</param>
152        /// <param name="Key">键名称。</param>

153        public static void RemoveKey(string FileName,string Section,string Key)
154        {
155            WindowsAPI.WritePrivateProfileString(Section, Key, null, FileName);
156        }

157
158        /// <summary>
159        /// 返回节集合。
160        /// </summary>

161        public SectionCollection Sections
162        {
163            get{return _Sections;}
164        }

165
166        /// <summary>
167        /// 获取文件详细信息对象。
168        /// </summary>

169        public FileInfo FileInfo
170        {
171            get{return new FileInfo(_FileName);}
172        }

173
174        /// <summary>
175        /// 将配置写入到DataSet中。
176        /// </summary>
177        /// <returns></returns>

178        public DataSet WriteDataSet()
179        {
180            DataSet ret=new DataSet();
181            foreach(Section s in this.Sections)
182            {
183                DataTable tb=ret.Tables.Add(s.SectionName);
184                tb.Columns.Add("Key");
185                tb.Columns.Add("Value");
186                foreach(Key k in s.Keys)
187                    tb.Rows.Add(new string[]{k.KeyName,k.Value});
188            }

189            return ret;
190        }

191
192        //加载INI配置文件
193        private void LoadDataStructure()
194        {
195            if(_FileName==null || _FileName=="")return;
196            _Sections.Clear(true);
197            try
198            {
199                byte[] temp1=new byte[32767];
200                byte[] temp2=new byte[32767];
201                string ret1="",ret2="";
202                //获取所有节
203                int l1=WindowsAPI.GetPrivateProfileString(nullnullnull,temp1, temp1.GetUpperBound(0), _FileName);
204                ret1=Encoding.GetEncoding(0).GetString(temp1);
205                ret1.Substring(0,ret1.IndexOf((char)0));
206                string[] s1=FormChar(ret1);
207                for(int i=0;i<s1.Length;i++)
208                {
209                    if(s1[i].Trim()!="")
210                    {
211                        Section section=_Sections.Add(s1[i],true);
212                        section.Keys.SetOwner(section);
213                        //获取所有键
214                        int l2=WindowsAPI.GetPrivateProfileSection(s1[i],temp2,temp2.GetUpperBound(0),_FileName);
215                        ret2=Encoding.GetEncoding(0).GetString(temp2).Substring(0,l2);
216                        string[] s2=FormChar(ret2);
217                        for(int j=0;j<s2.Length;j++)
218                        {
219                            int pp=s2[j].IndexOf("=");
220                            if(pp>0)
221                            {
222                                if(s2[j].Trim()!="")
223                                {
224                                    string k1=s2[j].Substring(0,pp).Trim();
225                                    string k2=s2[j].Substring(pp+1,s2[j].Length-pp-1);
226                                    Key key=section.Keys.Add(k1,k2,true);
227                                    key.SetOwner(section);
228                                }

229                            }

230                        }

231                    }

232                }

233            }

234            catch(Exception ex)
235            {
236                throw new Exception(ex.Message);
237            }

238        }

239
240        private static string[] FormChar(string s)
241        {
242            ArrayList ret=new ArrayList();
243            string[] ret1;
244            int pos=0;
245            while(true)
246            {
247                int p1=pos;
248                pos=s.IndexOf((char)0,pos);
249                if(pos<=0)break;
250                string s1=s.Substring(p1,pos-p1);
251                ret.Add(s1);
252                pos+=1;
253            }

254            ret1=new string[ret.Count];
255            for(int i=0;i<ret.Count;i++)
256                ret1[i]=(string)ret[i];
257            return ret1;
258        }

259
260        private static string[] FormChar(string s,bool trim)
261        {
262            ArrayList ret=new ArrayList();
263            string[] ret1;
264            int pos=0;
265            while(true)
266            {
267                int p1=pos;
268                pos=s.IndexOf((char)0,pos);
269                if(pos<=0)break;
270
271                string s1=s.Substring(p1,pos-p1);
272                ret.Add(s1);
273                pos+=1;
274            }

275            ret1=new string[ret.Count];
276            for(int i=0;i<ret.Count;i++)
277                ret1[i]=(string)ret[i];
278            return ret1;
279        }

280    }

281
282    /// <summary>
283    /// 节配置集合类。
284    /// </summary>

285    public class SectionCollection:IEnumerable
286    {
287        private ArrayList _Section=new ArrayList();
288
289        /// <summary>
290        /// 配置节的数量。
291        /// </summary>

292        public int Count
293        {
294            get{return _Section.Count;}
295        }

296
297        /// <summary>
298        /// 返回指定位置处的节对象。
299        /// </summary>

300        public Section this[int Index]
301        {
302            get{return (Section)_Section[Index];}
303        }

304
305        /// <summary>
306        /// 返回指定节名称的节对象。
307        /// </summary>

308        public Section this[string SectionName]
309        {
310            get
311            {
312                Section ret=new Section();
313                for(int i=0;i<_Section.Count;i++)
314                {
315                    Section v=(Section)_Section[i];
316                    if(v.SectionName.ToLower()==SectionName.ToLower())
317                    {
318                        ret=v;
319                        break;
320                    }

321                }

322                return ret;
323            }

324        }

325
326        //内部添加。
327        internal Section Add(string SectionName,bool inter)
328        {
329            Section ret=new Section(SectionName);
330            _Section.Add(ret);
331            return ret;
332        }

333
334        //内部添加。
335        internal Section Add(Section Object,bool inter)
336        {
337            _Section.Add(Object);
338            return Object;
339        }

340
341        //内部清除。
342        internal void Clear(bool inter)
343        {
344            _Section.Clear();
345        }

346
347        internal void Remove(int Index,bool inter)
348        {
349            _Section.Remove(_Section[Index]);
350        }

351
352        /// <summary>
353        /// 添加配置节对象。
354        /// </summary>
355        /// <param name="SectionName">节名称。</param>
356        /// <returns></returns>

357        public Section Add(string SectionName)
358        {
359            Section ret=new Section(SectionName);
360            ret.Keys.SetOwner(ret);
361            WindowsAPI.WritePrivateProfileSection(SectionName, new byte[0], IniFile._FileName);
362            _Section.Add(ret);
363            return ret;
364        }

365
366        /// <summary>
367        /// 清除INI文件中的所有节。
368        /// </summary>

369        public void Clear()
370        {
371            for(int i=_Section.Count-1;i>=0;i--)
372                this.Remove(i);
373        }

374
375        /// <summary>
376        /// 从集合中移除节。
377        /// </summary>
378        /// <param name="Index">节的索引位置。</param>

379        public void Remove(int Index)
380        {
381            Section ret=(Section)_Section[Index];
382            WindowsAPI.WritePrivateProfileString(ret.SectionName, nullnull, IniFile._FileName);
383            _Section.Remove(ret);
384        }

385
386        /// <summary>
387        /// 从集合中移除节。
388        /// </summary>
389        /// <param name="SectionName">节的名称。</param>

390        public void Remove(string SectionName)
391        {
392            Section ret=null;
393            for(int i=0;i<_Section.Count;i++)
394            {
395                Section v=(Section)_Section[i];
396                if(v.SectionName.ToLower()==SectionName.ToLower())
397                {
398                    ret=v;
399                    break;
400                }

401            }

402            if(ret==null)return;
403            WindowsAPI.WritePrivateProfileString(ret.SectionName, nullnull, IniFile._FileName);
404            _Section.Remove(ret);
405        }

406
407        /// <summary>
408        /// 检测指定的节是否包含在此集合中。
409        /// </summary>
410        /// <param name="SectionName">节名称。</param>
411        /// <returns></returns>

412        public bool Contains(string SectionName)
413        {
414            foreach(Section s in this)
415                if(s.SectionName.ToLower()==SectionName.ToLower())
416                    return true;
417            return false;
418        }

419
420        IEnumerator IEnumerable.GetEnumerator()
421        {
422            return new Section(this);
423        }

424    }

425
426    /// <summary>
427    /// 节配置类。
428    /// </summary>

429    public class Section:IEnumerator
430    {
431        private int nIndex;
432        SectionCollection enu;
433        private string _SectionName="";
434        private KeyCollection _Keys=new KeyCollection();
435            
436        public Section()
437        {
438        }

439
440        internal Section(SectionCollection sc)
441        {
442            enu=sc;
443            nIndex=-1;
444        }

445
446        /// <summary>
447        /// 构造类。
448        /// </summary>
449        /// <param name="SectionName">节名称。</param>

450        public Section(string SectionName)
451        {
452            _SectionName=SectionName;
453        }

454
455        /// <summary>
456        /// 返回此节中的所有键。
457        /// </summary>

458        public KeyCollection Keys
459        {
460            get{return _Keys;}
461        }

462
463        /// <summary>
464        /// 返回此节中的指定位置的键。
465        /// </summary>

466        public Key this[int Index]
467        {
468            get{return _Keys[Index];}
469        }

470
471        /// <summary>
472        /// 返回节名称。
473        /// </summary>

474        public string SectionName
475        {
476            get{return _SectionName;}
477            set{_SectionName=value;}
478        }

479
480        /// <summary>
481        /// 清除此节下的所有键。
482        /// </summary>

483        public void Clear()
484        {
485            WindowsAPI.WritePrivateProfileSection(_SectionName, new byte[0], IniFile._FileName);
486            _Keys.Clear();
487        }

488
489        /// <summary>
490        /// 移除此节。
491        /// </summary>

492        public void Remove()
493        {
494            WindowsAPI.WritePrivateProfileString(_SectionName, nullnull, IniFile._FileName);
495        }

496
497        void IEnumerator.Reset()
498        {
499            nIndex=-1;
500        }

501
502        object IEnumerator.Current
503        {
504            get{return enu[nIndex];}
505        }

506
507        bool IEnumerator.MoveNext()
508        {
509            nIndex++;
510            return(nIndex < enu.Count);
511        }

512    }

513
514    /// <summary>
515    /// 键集合类。
516    /// </summary>

517    public class KeyCollection:IEnumerable
518    {
519        private ArrayList _Key=new ArrayList();
520        private Section _Owner;
521
522        /// <summary>
523        /// 返回键数量。
524        /// </summary>

525        public int Count
526        {
527            get{return _Key.Count;}
528        }

529
530        internal void SetOwner(Section v)
531        {
532            _Owner=v;
533        }

534
535        /// <summary>
536        /// 返回指定位置的键。
537        /// </summary>

538        public Key this[int Index]
539        {
540            get
541            {
542                return (Key)_Key[Index];
543            }

544        }

545
546        /// <summary>
547        /// 返回指定名称的键。
548        /// </summary>

549        public Key this[string KeyName]
550        {
551            get
552            {
553                Key ret=new Key();
554                for(int i=0;i<_Key.Count;i++)
555                {
556                    Key v=(Key)_Key[i];
557                    if(v.KeyName.ToLower()==KeyName.ToLower())
558                    {
559                        ret=v;
560                        break;
561                    }

562                }

563                return ret;
564            }

565        }

566
567        //内部添加
568        internal Key Add(string KeyName,string Value,bool inter)
569        {
570            Key ret=new Key(KeyName,Value);
571            _Key.Add(ret);
572            return ret;
573
574        }

575
576        //内部清除
577        internal void Clear(bool inter)
578        {
579            _Key.Clear();
580        }

581
582        //移除
583        internal void Remove(int Index,bool inter)
584        {
585            _Key.Remove(_Key[Index]);
586        }

587
588        /// <summary>
589        /// 添加配置键对象。
590        /// </summary>
591        /// <param name="KeyName">键名称。</param>
592        /// <param name="Value">键值。</param>
593        /// <returns></returns>

594        public Key Add(string KeyName,string Value)
595        {
596            Key ret=new Key(KeyName,Value);
597            WindowsAPI.WritePrivateProfileString(_Owner.SectionName, KeyName, Value, IniFile._FileName);
598            _Key.Add(ret);
599            return ret;
600        }

601
602        /// <summary>
603        /// 清除INI文件中的所有节。
604        /// </summary>

605        public void Clear()
606        {
607            for(int i=_Key.Count-1;i>=0;i--)
608                this.Remove(i);
609        }

610
611        /// <summary>
612        /// 从集合中移除节。
613        /// </summary>
614        /// <param name="Index">节的索引位置。</param>

615        public void Remove(int Index)
616        {
617            Key ret=(Key)_Key[Index];
618            WindowsAPI.WritePrivateProfileString(_Owner.SectionName, ret.KeyName, null, IniFile._FileName);
619            _Key.Remove(ret);
620        }

621
622        /// <summary>
623        /// 从集合中移除节。
624        /// </summary>
625        /// <param name="KeyName">节的名称。</param>

626        public void Remove(string KeyName)
627        {
628            Key ret=null;
629            for(int i=0;i<_Key.Count;i++)
630            {
631                Key v=(Key)_Key[i];
632                if(v.KeyName.ToLower()==KeyName.ToLower())
633                {
634                    ret=v;
635                    break;
636                }

637            }

638            if(ret==null)return;
639            WindowsAPI.WritePrivateProfileString(_Owner.SectionName, ret.KeyName, null, IniFile._FileName);
640            _Key.Remove(ret);
641        }

642
643        /// <summary>
644        /// 检测指定的键是否包含在此集合中。
645        /// </summary>
646        /// <param name="KeyName">键名称。</param>
647        /// <returns></returns>

648        public bool Contains(string KeyName)
649        {
650            foreach(Key k in this)
651                if(k.KeyName.ToLower()==KeyName.ToLower())
652                    return true;
653            return false;
654        }

655
656        IEnumerator IEnumerable.GetEnumerator()
657        {
658            return new Key(this);
659        }

660    }

661
662    /// <summary>
663    /// 键类。
664    /// </summary>

665    public class Key:IEnumerator
666    {
667        private int nIndex;
668        KeyCollection enu;
669        private string _KeyName="";
670        private string _Value="";
671        private Section _Owner;
672
673        public Key()
674        {
675        }

676
677        internal Key(KeyCollection kc)
678        {
679            enu=kc;
680            nIndex=-1;
681        }

682
683        /// <summary>
684        /// 构造类。
685        /// </summary>
686        /// <param name="KeyName">键名称。</param>
687        /// <param name="Value">键值。</param>

688        public Key(string KeyName,string Value)
689        {
690            _KeyName=KeyName;
691            _Value=Value;
692        }

693
694        internal void SetOwner(Section v)
695        {
696            _Owner=v;
697        }

698
699        /// <summary>
700        /// 返回键名称。
701        /// </summary>

702        public string KeyName
703        {
704            get{return _KeyName;}
705            set{_KeyName=value;}
706        }

707
708        /// <summary>
709        /// 设置或返回键值。
710        /// </summary>

711        public string Value
712        {
713            get{return _Value;}
714            set{
715                _Value=value;
716                WindowsAPI.WritePrivateProfileString(_Owner.SectionName, _KeyName, _Value, IniFile._FileName);
717            }

718        }

719
720        /// <summary>
721        /// 移除此键。
722        /// </summary>

723        public void Remove()
724        {
725            WindowsAPI.WritePrivateProfileString(_Owner.SectionName, _KeyName, null, IniFile._FileName);
726        }

727
728        void IEnumerator.Reset()
729        {
730            nIndex=-1;
731        }

732
733        object IEnumerator.Current
734        {
735            get{return enu[nIndex];}
736        }

737
738        bool IEnumerator.MoveNext()
739        {
740            nIndex++;
741            return(nIndex < enu.Count);
742        }

743    }

744
745    internal class WindowsAPI
746    {
747        [DllImport("kernel32", EntryPoint="GetPrivateProfileSectionA")]
748        internal static extern int GetPrivateProfileSection(string lpAppName,byte[] lpReturnedString,int nSize,string filePath);
749
750        [DllImport("kernel32", EntryPoint="GetPrivateProfileStringA")]
751        internal static extern int GetPrivateProfileString(string section,string key,string def, byte[] retVal,int size,string filePath);
752        
753        [DllImport("kernel32.dll")]
754        internal extern static int WritePrivateProfileSection(string segName,byte [] sData,string fileName);
755
756        [DllImport("kernel32", EntryPoint="WritePrivateProfileStringA")]
757        internal static extern int WritePrivateProfileString(string section,string key,string val,string filePath);
758
759    }

760
761}
原文地址:https://www.cnblogs.com/faib/p/659442.html