C# INI 写入,读取,取得等操作

pre.ini 文件

;PRM1-患者编号NO
 [PRE_VALUE]
 PRM1="0000003"
 
 //写INI
private void cmd_Save_Click(object sender, EventArgs e)
  {
   try
   {
    if (!SetIniInfo("pre.ini", "PRE_VALUE", "PRM1", ComboBox.Text))
    {
     return;
    }
   }
   catch (Exception ex)
   {
    MessageBox.Show("INIファイルに書き込み失敗しました。\r\n" + ex.Message.ToString(), "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }
  }
//取得INI
  private void cmd_getIni_Click(object sender, EventArgs e)
  {
   string sTimeValue = "";
   GetIniAPI("pre.ini", "PRE_VALUE", "PRM1", ref lstr_Set5);
   //下面调用即可。
  }


 //*************************************************************************
        // @(f)
        // 技能    : pre.ini 系统信息取得
        // 返回值   : TRUE    - 正常終了
        //       : FALSE   - 異常終了
        // 参数     : 无
        // 技能説明  : pre.ini信息取得
        // 备考    :
        //*************************************************************************
        public static bool GetIniInfo()
        {
            bool returnValue;
            string strGetItem = "";
            returnValue = false;

            //'PRM1取得
            if (gbFNC_GetIniAPI("pre.ini", "PRE_VALUE", "PRM1",ref strGetItem) != true)
            {
                return returnValue;
            }
            string PRM1 = strGetItem;
            returnValue = true;
            return returnValue;
       }

        [DllImport("kernel32")]
        public static extern int WritePrivateProfileString(string section, string key,
                                                             string val, string filePath);
  [DllImport("kernel32")]
        public static extern int GetPrivateProfileString(string section, string key,
                                                          string def, StringBuilder retVal,
                                                          int size, string filePath);

  //*************************************************************************
  // @(f)
  // 技能    : pre.ini信息写入
  // 返回值   : TRUE  - 正常終了
  //       : FALSE - 異常終了
  // 参数     : wFileName    - 文件名
  //       : wSection     - ini节点名
  //       : wEntryName   - 输入的名
  //       : wSetting     - 写入的信息
  // 技能説明  : 系统函数「WritePrivateProfileString」によりpre.INI
  //       :Key(AppName、KeyName)等(wInfo)信息写入。
  // 备考    :
  //*************************************************************************

 public static bool SetIniInfo(string wFileName, string wSection, string wEntryName, string wSetting)
  {
   string lstr_IniFName = "";
   int llng_Ret;

            lstr_IniFName = Application.StartupPath + "\\" + wFileName;
            llng_Ret = Win32.WritePrivateProfileString(wSection, wEntryName, '\u0022' + wSetting + '\u0022', lstr_IniFName);
            return llng_Ret > 0;
  }


       //*************************************************************************
        // @(f)
        // 技能    : pre.ini指定的节点取得
        // 返回值   : True - 正常終了
        //       : False - 異常終了
     // 参数      : wFileName    - 文件名
   //       : wSection     - ini节点名
   //       : wEntryName   - 输入的名
        //       : wGetItem     - 取得节点值
        // 技能説明  : 系统函数「GetPrivateProfileString」によりpre.INIから
        //       : wSectionName,wEntryName信息取得。
        // 备考    : ini文件在实行环境下的使用する。
        //*************************************************************************
  public static bool GetIniAPI(string wFileName, string wSectionName, string wEntryName, ref string wGetItem)
        {

            bool returnValue = false;
            string strIniFName = "";
            StringBuilder strKeyName = new StringBuilder();
            string strValueKeyName = "";
            int lngRet;
            try
            {
                wGetItem = "";
                //Pathを設定
                strIniFName = Application.StartupPath + "\\" + wFileName;
                strKeyName.Capacity = 500;
                strValueKeyName = Strings.Space(500);
                //値を取得
                lngRet = Win32.GetPrivateProfileString(wSectionName, wEntryName, strValueKeyName, strKeyName, strKeyName.Capacity, strIniFName);
                string sTemp = strKeyName.ToString();
                wGetItem = sTemp;
                returnValue = true;
                return returnValue;
            }
            catch (Exception)
            {
                return returnValue;
            }
        }

  编辑

public static void EditIniFile(int curLine, string newLineValue, string patch)
        {
            FileStream fs = new FileStream(patch, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("Shift_JIS"));
            string line = sr.ReadLine();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; line != null; i++)
            {
                sb.Append(line + "\r\n");
                if (i != curLine - 1)
                    line = sr.ReadLine();
                else
                {
                    sr.ReadLine();
                    line = newLineValue;
                }
            }
            sr.Close();
            fs.Close();
            FileStream fs1 = new FileStream(patch, FileMode.Open, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs1, Encoding.GetEncoding("Shift_JIS"));
            sw.Write(sb.ToString());
            sw.Close();
            fs.Close();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ini读写代码详解实例,有很详细注释,保证满意; 预览截取一部分代码: /// <summary>   /// 读取INI文件中指定INI文件中的所有节点名称(Section)   /// </summary>   /// <param name="iniFile">Ini文件</param>   /// <returns>所有节点,没有内容返回string[0]</returns>   public static string[] INIGetAllSectionNames(string iniFile) { uint MAX_BUFFER = 32767; //默认为32767   string[] sections = new string[0]; //返回值   //申请内存   IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); uint bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile); if (bytesReturned != 0) { //读取指定内存的内容   string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString(); //每个节点之间用\0分隔,末尾有一个\0   sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); } //释放内存   Marshal.FreeCoTaskMem(pReturnedString); return sections; } /// <summary>   /// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)   /// </summary>   /// <param name="iniFile">Ini文件</param>   /// <param name="section">节点名称</param>   /// <returns>指定节点中的所有项目,没有内容返回string[0]</returns>   public static string[] INIGetAllItems(string iniFile, string section) { //返回值形式为 key=value,例如 Color=Red   uint MAX_BUFFER = 32767; //默认为32767   string[] items = new string[0]; //返回值   //分配内存   IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); uint bytesReturned = GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile); if (!(bytesReturned == MAX_BUFFER - 2) || (bytesReturned == 0)) { string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned); items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries); } Marshal.FreeCoTaskMem(pReturnedString); //释放内存   return items; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值