INI 文件的读写操作

时间:2021-03-27 16:47:08

在C#中对INI文件进行读写操作,在此要引入using System.Runtime.InteropServices; 命名空间,具体方法如下:

  #region  变量

        private  static readonly string strFilePath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "App.ini";//INI文件路径

        #endregion 

        #region  私有方法

        /// <summary>
/// 写入INI文件
/// </summary>
/// <param name="section">节点名称[如[TypeName]]</param>
/// <param name="key">键</param>
/// <param name="val">值</param>
/// <param name="filepath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filepath); /// <summary>
/// 读取INI文件
/// </summary>
/// <param name="section">节点名称</param>
/// <param name="key">键</param>
/// <param name="def">值</param>
/// <param name="retval">stringbulider对象</param>
/// <param name="size">字节大小</param>
/// <param name="filePath">文件路径</param>
/// <returns></returns>
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval, int size, string filePath); #endregion #region 公共方法 public static string GetValue(string section, string key)
{
try
{
int size = 2048;
StringBuilder temp = new StringBuilder(size);
GetPrivateProfileString(section, key, "", temp, size, strFilePath);
return temp.ToString();
}
catch(Exception e)
{
throw new Exception(e.Message);
} } public static bool WriteValue( string section, string key, string value)
{
try
{
long length= WritePrivateProfileString(section, key, value, strFilePath);
return length>0;
}
catch(Exception e)
{
throw new Exception(e.Message);
}
} #endregion