C# 读写编辑INI文件的操作

  [DllImport("kernel32")]

  private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

  [DllImport("kernel32")]

  private static extern long GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

  #region 创建文件

  public static void CreateFile(string path)

  {

  if (!string.IsNullOrEmpty(path))

  {

  try

  {

  string dr = Path.GetDirectoryName(path);

  if (!Directory.Exists(dr))

  {

  Directory.CreateDirectory(dr);

  }

  if (!File.Exists(path))

  {

  FileStream fs = File.Create(path);

  fs.Close();

  }

  }

  catch (Exception e)

  {

  }

  }

  }

  #endregion

  #region 写ini文件

  ///ini文件中的节名

  ///ini 文件中的健

  ///要写入该健所对应的值

  ///ini文件路径

  public static bool WriteIniData(string Section, string key, string val, string inifilePath)

  {

  if (File.Exists(inifilePath))

  {

  long opSt = WritePrivateProfileString(Section, key, val, inifilePath);

  if (opSt == 0)

  {

  return false;

  }

  else

  {

  return true;

  }

  }

  else

  {

  CreateFile(inifilePath);

  long opSt = WritePrivateProfileString(Section, key, val, inifilePath);

  if (opSt == 0)

  {

  return false;

  }

  else

  {

  return true;

  }

  }

  }

  #endregion

  #region 取ini文件

  /// 节点名称

  /// 对应的key

  /// 读不到值时返回的默认值

  /// 文件路径

  public static string ReadIniData(string section, string key, string noText, string iniFilePath)

  {

  if (File.Exists(iniFilePath))

  {

  StringBuilder temp = new StringBuilder(1024);

  long k = GetPrivateProfileString(section, key, noText, temp, 1024, iniFilePath);

  if (k != 0)

  {

  return temp.ToString();

  }

  else

  {

  return string.Empty;

  }

  }

  else

  {

  return string.Empty;

  }

  }

  #endregion