C#读写ini文件操作

ini文件,是windows操作系统下的配置文件,ini文件是一种按照特点方式排列的文本文件,它的构成分为三部分,结构如下:

[Section1]
key 1 = value2
key 1 = value2
……
[Section2]
key 1 = value1
key 2 = value2
……


文件由若干个段落(section)组成,每个段落又分成若干个键(key)和值(value)。

 

C#和Win32 API函数

        C#并不像C++,拥有属于自己的类库。C#使用的类库是.Net框架为所有.Net程序开发提供的一个共有的类库——.Net FrameWork SDK。虽然.Net FrameWork SDK内容十分庞大,功能也非常强大,但还不能面面俱到,至少它并没有提供直接操作INI文件所需要的相关的类。在本文中,C#操作INI文件使用的是Windows系统自带Win32的API函数——WritePrivateProfileString()和GetPrivateProfileString()函数。这二个函数都位于“kernel32.dll”文件中。
        我们知道在C#中使用的类库都是托管代码(Managed Code)文件,而Win32的API函数所处的文件,都是非托管代码(Unmanaged Code)文件。这就导致了在C#中不可能直接使用这些非托管代码文件中的函数。好在.Net框架为了保持对下的兼容,也为了充分利用以前的资源,提出了互操作,通过互操作可以实现对Win32的API函数的调用。互操作不仅适用于Win32的API函数,还可以用来访问托管的COM对象。C#中对Win32的API函数的互操作是通过命名空间“System.Runtime.InteropServices”中的“DllImport”特征类来实现对windows api函数的使用,它的主要作用是指示此属性化方法是作为非托管DLL的输出实现的。

 

C#申明INI文件的写操作函数WritePrivateProfileString():

1 [DllImport("kernel32")] 
2 private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); 
3 section: 要写入的段落名
4 key: 要写入的键,如果该key存在则覆盖写入
5 val: key所对应的值
6 filePath: INI文件的完整路径和文件名

 

C#申明INI文件的读操作函数GetPrivateProfileString():

1 [DllImport("kernel32")]
2 private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath); 
3 section:要读取的段落名
4 key: 要读取的键
5 defVal: 读取异常的情况下的缺省值
6 retVal: key所对应的值,如果该key不存在则返回空值
7 size: 值允许的大小
8 filePath: INI文件的完整路径和文件名

 

 

下面是我写的一个例子:

 

当我输入完后,点击录入按钮时候,就会写入到ini文件中:

当点击读取按钮的时候就会把INI文件中的节点信息的值填充到窗体中的文本框中

 

后台代码:

在项目名称空间的上方要添加以下的引用:

using System.Runtime.InteropServices;//引用命名空间,该空间为了调用windows api。

 1       #region "声明变量"
 2 
 3         /// <summary>
 4         /// 写入INI文件
 5         /// </summary>
 6         /// <param name="section">节点名称[如[TypeName]]</param>
 7         /// <param name="key"></param>
 8         /// <param name="val"></param>
 9         /// <param name="filepath">文件路径</param>
10         /// <returns></returns>
11         [DllImport("kernel32")]
12         private static extern long WritePrivateProfileString(string section,string key,string val,string filepath);
13         /// <summary>
14         /// 读取INI文件
15         /// </summary>
16         /// <param name="section">节点名称</param>
17         /// <param name="key"></param>
18         /// <param name="def"></param>
19         /// <param name="retval">stringbulider对象</param>
20         /// <param name="size">字节大小</param>
21         /// <param name="filePath">文件路径</param>
22         /// <returns></returns>
23         [DllImport("kernel32")]
24         private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filePath);
25         #endregion    


申明全局路径的变量:

1         private string strFilePath = Application.StartupPath + "\\MyConfig.ini";//获取INI文件路径
2         private string strSec = ""; //INI文件名


声明下,我的ini文件是新建在debug下面的:

 1        private void bt_write_Click(object sender, EventArgs e)
 2         {
 3             try
 4             {
 5 
 6                 //根据INI文件名设置要写入INI文件的节点名称
 7                 //此处的节点名称完全可以根据实际需要进行配置
 8                 strSec = Path.GetFileNameWithoutExtension(strFilePath);
 9                 WritePrivateProfileString(strSec, "user", text_user.Text.Trim(), strFilePath);
10                 WritePrivateProfileString(strSec, "password", text_password.Text.Trim(), strFilePath);
11                 MessageBox.Show("录入成功");
12 
13             }
14             catch (Exception ex)
15             {
16                 MessageBox.Show(ex.Message.ToString());
17 
18             }
19 
20         }

 

//  读取按钮事件
 1 private void bt_read_Click(object sender, EventArgs e)
 2         {
 3             if (File.Exists(strFilePath))//读取时先要判读INI文件是否存在
 4             {
 5 
 6                 strSec = Path.GetFileNameWithoutExtension(strFilePath);
 7                 text_user.Text = ContentValue(strSec, "user");
 8                 text_password.Text = ContentValue(strSec, "password");
 9             }
10             else
11             {
12                 MessageBox.Show("MyConfig.ini文件不存在");
13             }
14         }


在读取的时候用到了自定义读取函数的方法,在该方法中调用了系统函数,

1         private string ContentValue(string Section, string key)
2         {
3             StringBuilder temp = new StringBuilder(32);
4             GetPrivateProfileString(Section, key, "", temp, 32, strFilePath);
5             return temp.ToString();
6         }


以上所述的就是简单的用C#语言操作INI文件的过程,只用到了系统函数中的两个(写入函数和读取函数)还有其他的函数比如说时删除INI文件函数等等,删除INI文件函数其实就是把键对应的值设置为null就可以了。自动登录和连接设置都用到了INI文件。

 

作者:orange1438
出处:http://www.cnblogs.com/orange1438/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

posted @ 2013-08-30 21:16  橙&子  阅读(1136)  评论(0编辑  收藏  举报