码迷,mamicode.com
首页 > 其他好文 > 详细

INI 文件的读写操作

时间:2016-07-30 11:56:41      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

在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

  

INI 文件的读写操作

标签:

原文地址:http://www.cnblogs.com/wisdo/p/5720596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!