• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#读写ini文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
主要思路是调用Win32 API。
1.引入命名空间
using System.Runtime.InteropServices;
2.声明(把一个Win32 API函数转成C#函数)
        //声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        
//声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
3.调用
//写一个config.ini文件

private
 void Save_Ini()
        {
            
string s = System.Windows.Forms.Application.ExecutablePath;
            
//在当前目录下,写一个config.ini文件
            string path = s.ToLower().Replace("mediaconvert.exe""config.ini");

            
string configureNode = "DataBaseConfigure";//配置节

            
string key1 = "DataBase";//键名
            string key1_Value = "DataBaseName";//键值

            
string key2 = "Server";
            
string key2_Value = "ServerName";

            
string key3 = "UserId";
            
string key3_Value = "1";

            WritePrivateProfileString(configureNode, key1, key1_Value, path);
            WritePrivateProfileString(configureNode, key2, key2_Value, path);
            WritePrivateProfileString(configureNode, key3, key3_Value, path);
            

            /*最后在exe文件的同目录下,生成一个config.ini文件,内容应如下:
             * [DataBaseConfigure]
             * DataBase=DataBaseName
             * Server=ServerName
             * UserId=1
             
*/
        }

//读取config.ini文件中的配置

private
 void Read_Ini()
        {
            
string s = System.Windows.Forms.Application.ExecutablePath;
            
//取得config.ini路径
            string path = s.ToLower().Replace("mediaconvert.exe""config.ini");

            StringBuilder str 
= new StringBuilder(255);
            
//取得配置节[DataBaseConfigure]的DataBase键的值
            GetPrivateProfileString("DataBaseConfigure""DataBase""", str, 255, path);
            
//对话框中结果应该为 DataBase:DataBaseName
            System.Windows.Forms.MessageBox.Show("DataBase:" + str.ToString());
        }

C#使用系统Api,最头疼的问题就是Api中的数据类型在C#中,如何对应的问题。
这个网站http://www.pinvoke.net列出了大多系统Api在此C#或VB.Net中的对应声明,很详细。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# json、xml序列化发布时间:2022-07-13
下一篇:
c#移动鼠标到指定位置发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap