转载,原处不详,我个人用注册表 C#读写INI文件 虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。 INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value) [Section] Key=Value VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。 INIFILE类:using System;using System.IO;using System.Runtime.InteropServices;//因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices 命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。using System.Text;namespace Ini{ public class IniFile { public string path; //INI文件名 [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section,string key,string val,string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath); //声明读写INI文件的API函数 public IniFile(string INIPath) { path = INIPath; } //类的构造函数,传递INI文件名 public void IniWriteValue(string Section,string Key,string Value) { WritePrivateProfileString(Section,Key,Value,this.path); } //写INI文件 public string IniReadValue(string Section,string Key) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path); return temp.ToString(); } //读取INI文件指定 }} 调用INIFILE类: 新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。 增加如下代码:using Ini; //创建命名空间//当窗体关闭时保存窗体坐标private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) { IniFile ini = new IniFile("C:\\test.ini"); ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString() ); ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString() ); //ToString方法将数字转换为字符串 }//当窗体启动时,读取INI文件的值并赋值给窗体 private void Form1_Load(object sender, System.EventArgs e) { IniFile ini = new IniFile("C:\\test.ini"); Point p=new Point() ; if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!="")) //判断返回值,避免第一次运行时为空出错 { p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" )); p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" )); // int.Parse将字符串转换为int this.Location =p; } }
如果cs程序文件名叫 Hello.exe, 那么就写一个 Hello.exe.config 的配置文件
写法和web.config类似, 可以把配置参数全写在这里头
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="conString" value="data source=TEASY-TCI\EDU001;database=PerResource;user id=person;pwd=person" />
<add key="conString2" value="data source=TEASY-TCI\EDU001;database=WebServiceDB;user id=person;pwd=person" />
<add key="conString3" value="data source=tfs;database=oa;user id=guest1;pwd=transcosmos" />
</appSettings>
</configuration>读取
string conString = ConfigurationSettings.AppSettings["conString"];
MessageBox.Show(conString,conString);
UINT GetPrivateProfileInt(
LPCTSTR lpAppName, // section name
LPCTSTR lpKeyName, // key name
INT nDefault, // return value if key name not found
LPCTSTR lpFileName // initialization file name
);
DWORD GetPrivateProfileString(
LPCTSTR lpAppName, // section name
LPCTSTR lpKeyName, // key name
LPCTSTR lpDefault, // default string
LPTSTR lpReturnedString, // destination buffer
DWORD nSize, // size of destination buffer
LPCTSTR lpFileName // initialization file name
);具体方法上面的兄台讲的已经很清楚了,只是GetPrivateProfileString由于要给一个返回string的buffer,所以用了GetPrivateProfileString,
而GetPrivateProfileInt 则相对简单得多。
以下是我做得一个例子,用来获取Sql server的连接字符串的#define WEB
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;using System.Configuration ;namespace Wonder.Lib.Base
{
/// <summary>
/// 从配置文件中取得数据库连接字符串
/// 默认:Web方式,从Web.config 中取 GetConnStrWeb()
/// 桌面方式:从Windows目录下的eii.ini 中取 GetConnStrDeskTop()
/// </summary>
public class SQLConnString
{
private const string USER = "User id";
private const string PASS = "password";
private const string SOURCE = "data source";
private const string CATALOG= "catalog";
private const string SIZE = "size"; private const string SECTION= "DataBase";
private static string INI_FILE= System.Environment.GetEnvironmentVariable("WINDIR")+"\\eii.ini";
// @"C:\Winnt\system32\ini.dll"; [DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
[DllImport("kernel32")]
private static extern uint GetPrivateProfileInt(string section,string key,uint size,string filePath);
public SQLConnString()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 取得web程序的数据库连接字符串
/// </summary>
/// <returns></returns>
private static string GetConnStrWeb()
{
return ConfigurationSettings.AppSettings["Wonder_DL_DataBase_Conn_String"];
} /// <summary>
/// 取得CS程序的连接字符串
/// </summary>
/// <returns></returns>
private static string GetConnStrDeskTop()
{
string ReturnText;
ReturnText="persist security info=False; packet size="+GetPrivateProfileInt(SECTION,SIZE,4096,INI_FILE).ToString()+";data source="+IniReadValue(SOURCE)
+";initial catalog="+IniReadValue(CATALOG)+";user id="
+IniReadValue(USER)+";password="+IniReadValue(PASS);
// ReturnText="provider=SQLOLEDB;data source=172.16.36.222"+
// ";initial catalog=RemoteEdu;user id=sa"
// +";password=1234567890";
return ReturnText;
} /// <summary>
/// 取得连接字符串
/// </summary>
/// <returns></returns>
public static string GetConnStr()
{
#if WEB
return GetConnStrWeb();
#else
return GetConnStrDeskTop();
#endif
}
/// <summary>
/// 从配置文件中取配置
/// </summary>
/// <param name="Key">键</param>
/// <returns></returns>
public static string IniReadValue(string Key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(SECTION,Key,"",temp,255,INI_FILE);
return temp.ToString();
} }
}
//-------------------------------------------------
以下是配置文件
[DataBase]
catalog=RemoteEdu
data source=172.16.36.222
User id=sa
password=1234567890
size = 10240
//-----------------------------------当然你也可以通过直接读文本文件来取得,反正c#中已经封装的很简单。而且用自己的格式更方便引用。
而GetPrivateProfileInt 则相对简单得多。==>具体方法上面的兄台讲的已经很清楚了,只是GetPrivateProfileString由于要给一个返回string的buffer,所以用了StringBuilder ,
而GetPrivateProfileInt 则相对简单得多。
MessageBox.Show(ls,ls);