Winfrom修改AppConfig之坑

Winfrom的AppConfig大多数情况下,我们都是用来读取一些简单的配置

偶尔可能会遇到存取一两个变量,这样的情况下,我们不会单独见配置文件,也不会启用ini文件,可能为了方便

顺手用一下appconfig。但是 appconfig读取容易 修改可是很坑的 

使用系统只带的方法,可能不会永久保存修改(具体问题请参考C#之app.config、exe.config和vshost.exe.config作用区别

这种情况下 我们就只能采用xml文件的读写方式去获取和设置值了

方法如下:

    public sealed class AppConfigHelper
    {

        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        public static string GetValue(string key)
        {
            try
            {
                //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                // return  config.AppSettings.Settings[key].Value;
                return ConfigurationManager.AppSettings[key].ToString().Trim() ?? String.Empty;
            }
            catch
            {

                return string.Empty;
            }

            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

                var xNode = xDoc.SelectSingleNode("//appSettings");

                var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");

                if (xElem != null)
                {
                    return xElem.Attributes["value"].Value;
                }
                return string.Empty;
            }
            catch (Exception)
            {

                return string.Empty;
            }

           
        }


        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        public static void SetValue(string key, string value)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
                var xNode = xDoc.SelectSingleNode("//appSettings");
                var xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
                if (xElem != null) xElem.SetAttribute("value", value);
                else
                {
                    var xNewElem = xDoc.CreateElement("add");
                    xNewElem.SetAttribute("key", key);
                    xNewElem.SetAttribute("value", value);
                    xNode.AppendChild(xNewElem);
                }
                xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            }
            catch (Exception)
            {

            }

            try
            {
                ConfigurationManager.AppSettings.Set(key, value);
                //System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                //ConfigurationManager.AppSettings.Set(key, value);
                //config.AppSettings.Settings[key].Value = value;
                //config.SaveAs("App.config");
            }
            catch(Exception ex)
            {
                Log.LogRecorder.AddEventRec(ex.Message);
            }

        }
    }

注释的代码就是系统自带方式读取和写入,这种方式在程序重启后,会丢失掉已经修改后appconfig中的值 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以通过以下步骤在 WinForm修改 Excel 文件: 1. 在 Visual Studio 中创建 WinForm 应用程序。 2. 在界面中添加一个 Button 控件和一个 DataGridView 控件。 3. 在 Button 的 Click 事件中添加以下代码: ``` private void button1_Click(object sender, EventArgs e) { // 打开文件对话框选择 Excel 文件 OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "Excel 文件|*.xls;*.xlsx"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { // 获取 Excel 文件路径 string filePath = openFileDialog1.FileName; // 连接 Excel 数据源 string connectionString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={filePath};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; OleDbConnection connection = new OleDbConnection(connectionString); connection.Open(); // 读取 Excel 数据 OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); // 在 DataGridView 控件中显示数据 dataGridView1.DataSource = dataTable; // 修改数据 dataTable.Rows[0]["Column1"] = "New Value"; dataTable.Rows[1]["Column2"] = "Another New Value"; // 更新 Excel 数据 OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter); adapter.Update(dataTable); // 关闭连接 connection.Close(); } } ``` 这样,当用户点击 Button 控件时,就会打开文件对话框,让用户选择 Excel 文件,并将文件中的数据显示在 DataGridView 控件中。然后,你可以通过修改 DataTable 中的数据来更新 Excel 文件中的数据。最后,使用 OleDbDataAdapter 的 Update 方法将修改后的数据写回 Excel 文件中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值