码迷,mamicode.com
首页 > Windows程序 > 详细

C#在winform中读写ini文件

时间:2017-12-14 19:23:41      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:cto   cti   tin   else   code   lines   params   tar   get   

  1     class WY_INI
  2     {
  3         static string IniFileName;
  4         static char[] TrimChar = {  , \t };
  5         public string[] GetSects()
  6         {
  7             string[] Sects = null;
  8 
  9             if (File.Exists(IniFileName))
 10             {
 11                 string str;
 12                 ArrayList ls = new ArrayList();
 13                 TextReader tr = File.OpenText(IniFileName);
 14                 while ((str = tr.ReadLine()) != null)
 15                 {
 16                     str = str.Trim();
 17                     if ((str.StartsWith("[")) && (str.EndsWith("]")))
 18                         ls.Add(str);
 19                 }
 20                 tr.Close();
 21                 if (ls.Count > 0)
 22                 {
 23                     Sects = new string[ls.Count];
 24                     for (int i = 0; i < ls.Count; i++)
 25                     {
 26                         Sects[i] = ls[i].ToString();
 27                     }
 28                 }
 29             }
 30             return Sects;
 31         }
 32         public static void PutINI(string sect, string keystr, string valuestr, string IniFileName)
 33         {
 34             ArrayList ls = new ArrayList();
 35             bool SectOK = false;
 36             bool SetOK = false;
 37             if (File.Exists(IniFileName))
 38             {
 39                 int pos1;
 40                 string substr;
 41                 string str;
 42                 TextReader tr = File.OpenText(IniFileName);
 43                 while ((str = tr.ReadLine()) != null)
 44                 {
 45                     ls.Add(str);
 46                 }
 47                 tr.Close();
 48                 //开始寻找关键字,如果找不到,则在这段的最后一行插入,然后再整体的保存一下INI文件。
 49                 for (int i = 0; i < ls.Count; i++)
 50                 {
 51                     str = ls[i].ToString();
 52                     if (str.StartsWith("[") && SectOK) //先判断是否到下一段中了,如果本来就是最后一段,那就有可能永远也不会发生了。
 53                     {
 54                         SetOK = true; //如果在这一段中没有找到,并且已经要进入下一段了,就直接在这一段末添加了。
 55                         ls.Insert(i, keystr.Trim() + "=" + valuestr);
 56                         break;//如果到下一段了,则直接退出就好。
 57                     }
 58                     if (SectOK)
 59                     {
 60                         pos1 = str.IndexOf("=");
 61                         if (pos1 > 1)
 62                         {
 63                             substr = str.Substring(0, pos1);
 64                             substr.Trim(TrimChar);
 65                             //如果在这一段中找到KEY了,直接修改就好了。
 66                             if (substr.Equals(keystr, StringComparison.OrdinalIgnoreCase) && SectOK) //是在此段中,并且KEYSTR前段也能匹配上。
 67                             {
 68                                 SetOK = true;
 69                                 ls[i] = keystr.Trim() + "=" + valuestr;
 70                                 break;
 71                             }
 72                         }
 73                     }
 74                     if (str.StartsWith("[" + sect + "]")) //判断是否到需要的段中了。
 75                         SectOK = true;
 76                 }
 77                 if (SetOK == false)
 78                 {
 79                     SetOK = true;
 80                     if (!SectOK) //如果没有找到段,则需要再添加段。
 81                     {
 82                         ls.Add("[" + sect + "]");
 83                     }
 84                     ls.Add(keystr.Trim() + "=" + valuestr);
 85                 }
 86             } //如果文件不存在,则需要建立文件。
 87             else
 88             {
 89                 ls.Clear();
 90                 ls.Add("##文件创建:" + DateTime.Now.ToString() + "##");
 91                 ls.Add("[" + sect + "]");
 92                 ls.Add(keystr.Trim() + "=" + valuestr);
 93             }
 94             //if (File.Exists(IniFileName)) //删除源文件。
 95             //{
 96             //    File.Delete(IniFileName);
 97             //}
 98             TextWriter tw = File.CreateText(IniFileName);
 99             //string[] strList = new string[ls.Count];
100             for (int i = 0; i < ls.Count; i++)
101             {
102                 //strList[i] = ls[i].ToString();
103                 tw.WriteLine(ls[i].ToString());
104             }
105             tw.Flush();
106             tw.Close();
107             //File.WriteAllLines(IniFileName, strList);
108         }
109         public static string GetINI(string sect, string keystr, string defaultstr, string IniFileName)
110         {
111             string retstr = defaultstr;
112             if (File.Exists(IniFileName))
113             {
114                 bool SectOK = false;
115                 int pos1;
116                 string substr;
117                 string str;
118                 ArrayList ls = new ArrayList();
119                 TextReader tr = File.OpenText(IniFileName);
120                 while ((str = tr.ReadLine()) != null)
121                 {
122                     str = str.Trim();
123                     if (str.StartsWith("[") && SectOK) //先判断是否到下一段中了。
124                     {
125                         break;//如果到下一段了,则直接退出就好。
126                     }
127                     if (SectOK)
128                     {
129                         pos1 = str.IndexOf("=");
130                         if (pos1 > 1)
131                         {
132                             substr = str.Substring(0, pos1);
133                             substr.Trim(TrimChar);
134                             if (substr.Equals(keystr, StringComparison.OrdinalIgnoreCase)) //是在此段中,并且KEYSTR前段也能匹配上。
135                             {
136                                 retstr = str.Substring(pos1 + 1).Trim(TrimChar);
137                                 break;
138                             }
139                         }
140                     }
141                     if (str.StartsWith("[" + sect + "]")) //判断是否到需要的段中了。
142                         SectOK = true;
143                 }
144                 tr.Close();
145             }
146             return retstr;
147         }
148         //读整数 
149         public static int GetINI(string Section, string Ident, int Default,string IniFileName)
150         {
151             string intStr = GetINI(Section, Ident, Convert.ToString(Default),IniFileName);
152             try
153             {
154                 return Convert.ToInt32(intStr);
155             }
156             catch
157             {
158                 return Default;
159             }
160         }
161 
162         //写整数 
163         public static void PutINI(string Section, string Ident, int Value, string IniFileName)
164         {
165             PutINI(Section, Ident, Value.ToString(),IniFileName);
166         }
167 
168         //读布尔 
169         public static bool ReadBool(string Section, string Ident, bool Default, string IniFileName)
170         {
171             try
172             {
173                 return Convert.ToBoolean(GetINI(Section, Ident, Convert.ToString(Default),IniFileName));
174             }
175             catch
176             {
177                 return Default;
178             }
179         }
180         //写Bool 
181         public static void PutINI(string Section, string Ident, bool Value,string IniFileName)
182         {
183             PutINI(Section, Ident, Convert.ToString(Value),IniFileName);
184         }
185 
186         /////////////////////////////////////////////////////////////////////////
187         //使用此INI文件的特例(自己使用)
188         public string GetParam(string KeyStr, string Default,string IniFileName)
189         {
190             string str;
191             str = GetINI("Params", KeyStr, "???", IniFileName);
192             if (str == "???")
193             {
194                 PutINI("Params", KeyStr, Default, IniFileName);
195                 str = Default;
196             }
197             return str;
198         }
199         public void UpdateParam(string KeyStr, string ValueStr,string IniFileName)
200         {
201             PutINI("Params", KeyStr, ValueStr, IniFileName);
202         }
203     }

路径必须用全路径

       static void Main(string[] args)
        {

            string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\config5.ini"; 
           Console.WriteLine("获取当前路径:" + testPath2);
            int temp;
            int temp2;
            Random rand = new Random();
            Random rand2 = new Random();
            string s;
            while (true)
            {
                temp2 = rand.Next(1, 10);
                temp = rand.Next(1, 1000);
                ZT_INI1.PutINI("system" + temp2, "print" + temp, "随机数" + temp, path);
                s=ZT_INI1.GetINI("system" + temp2, "print" + temp, "随机数" + temp, path);
                Console.WriteLine(s);

            }
        }

改良过了,不会出现空行和丢失问题,测试的时候写了个循环跑了一会儿~~~~

C#在winform中读写ini文件

标签:cto   cti   tin   else   code   lines   params   tar   get   

原文地址:http://www.cnblogs.com/wy0904/p/8038851.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!