zoukankan      html  css  js  c++  java
  • C#之使用app.config可记录数据,下次打开可读取记录的数据

    一、背景

    如下图所示,我通过open..按键打开了某个文件,之后我再把app给关闭掉,当再次打开app的时候,在textBox.Text上显示上一次打开的文件路径。通过使用app.config可以保存这个路径,再次打开app时候再从app.config里边读取出来。

    二、软件测试

    1、在App.config中添加所要保存的配置信息。如下图所示:

    2、在解决方案资源管理器项目中添加引用后增加System.Configuration。如下图所示:

    3、程序源码:

    using System.Configuration;
    
    /// 在配置信息中根据指定的键获取值。
            ///
            /// 指定的键。
            public static string GetConfigurationValue(string key)
            {
                return ConfigurationManager.AppSettings[key];
            }
            /// 在配置信息中修改指定键的值。
            public static string FileName=System.IO.Path.GetFileName(Application.ExecutablePath);           //得到文件
            public static void SetConfigurationValue(string key, string value)
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(FileName);
                config.AppSettings.Settings[key].Value = value;
                config.Save(ConfigurationSaveMode.Modified);
                System.Configuration.ConfigurationManager.RefreshSection("appSettings");
            }
    
    

    4、应用:
    我通过按键浏览打开某个文件之后得到文件的路径,使用SetConfigurationValue把文件的路径值保存在app.config中。

    private void Openfilebutton_Click(object sender, EventArgs e)
            {
                    OpenFileDialog fileEds = new OpenFileDialog();  //定义新的文件打开位置软件
                    fileEds.Filter = "EDS文件|*.eds";               //设置文件后缀过滤
                    fileEds.RestoreDirectory = true;
                              
                   if (fileEds.ShowDialog() == DialogResult.OK)    //如果有选择打开文件
                    {
                        SetConfigurationValue("folder", fileEds.FileName);  
                    }
               
                
            }
    

    每次重新打开APP,使用GetConfigurationValue会去app.config里边读取上次修改的数据,这样我就可以在textBox.Text上显示上一次打开的文件路径。

    private void CanOpenDevice_Load(object sender, EventArgs e)
            {
                if(File.Exists(GetConfigurationValue("folder")))
                {
                    GloableVar.filepath = GetConfigurationValue("folder");//得到文件路径
                }
            } 
    

    三、参考文档

    http://blog.sina.com.cn/s/blog_8ae8fed10102w8g6.html
    http://blog.csdn.net/celte/article/details/9749389
    http://blog.csdn.net/Yujie_Yang/article/details/52298688
    http://www.itkeyword.com/doc/9471404982607029x123/winform-c

    by 羊羊得亿
    2017-08-03 ShenZhen

  • 相关阅读:
    Redis缓存穿透和雪崩
    Redis主从复制
    Redis发布订阅
    IO多路复用
    Synchronized解读
    日志导致jvm内存溢出相关问题
    tomcat及springboot实现Filter、Servlet、Listener
    MySQL主从复制针对trigger的特殊处理
    二、变量/常量/数据类型
    Ubuntu21.04 / Linux Mint20.2 安装 TradingView分析软件
  • 原文地址:https://www.cnblogs.com/yangxuli/p/7279936.html
Copyright © 2011-2022 走看看