在Winform中动态读写app.config文件

这篇具有很好参考价值的文章主要介绍了在Winform中动态读写app.config文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在Winform中动态读写app.config文件

https://blog.csdn.net/kingmax54212008/article/details/38987277?spm=1001.2101.3001.6650.7&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7ERate-7-38987277-blog-82746084.235%5Ev36%5Epc_relevant_default_base3&utm_relevant_index=12

1、  首先需要在项目中引用:System.Configuration

2、  通过OpenExeConfiguration()这个方法来对配置文件进行操作

     若当前项目的配置文件如下:

  1.  
    <?xml version="1.0"?>
  2.  
    <configuration>
  3.  
    <appSettings>
  4.  
    <clear />
  5.  
    <add key="DataSource" value=".\SQL2005"/>
  6.  
    <!-- 数据库服务地址-->
  7.  
    <add key="InitialCatalog" value="db"/>
  8.  
    <!-- 数据库名称-->
  9.  
    <add key="UserId" value="sa"/>
  10.  
    <!-- 用户名-->
  11.  
    <add key="Password" value="sa"/>
  12.  
    <!-- 这个密码是加密之后的-->
  13.  
    <add key="ConnectTimeout" value="1000"/>
  14.  
    </appSettings>
  15.  
    <startup>
  16.  
    <supportedRuntime version="v2.0.50727"/>
  17.  
    </startup>
  18.  
    </configuration>

 

需要对上面appSettings的键值作修改,如下代码所示:

  1.  
    string path = Application.StartupPath + "\\ASSEMLY.exe";
  2.  
    Configuration config = ConfigurationManager.OpenExeConfiguration(path);
  3.  
    config.AppSettings.Settings.Clear();
  4.  
     
  5.  
    config.AppSettings.Settings.Add("DataSource", this.DataSource);
  6.  
    config.AppSettings.Settings.Add("InitialCatalog", this.InitialCatalog);
  7.  
    config.AppSettings.Settings.Add("UserId", this.UserId);
  8.  
    config.AppSettings.Settings.Add("Password", this.DePassword);
  9.  
    config.AppSettings.Settings.Add("ConnectTimeout", this.ConnectTimeout.ToString());
  10.  
     
  11.  
    // 保存对配置文件所作的更改
  12.  
    config.Save(ConfigurationSaveMode.Modified);
  13.  
    // 强制重新载入配置文件的ConnectionStrings配置节
  14.  
    ConfigurationManager.RefreshSection("appSettings");

 

  其中它是不能直接修改健值的,是在修改之前要删除该键值,然后重新添加

  同是,上面的只是对AppSettings进行操作,其实也可以对ConnectionStrings、SectionGroups、Sections进行操作

 

读取所有的AppSettings的值

 

StringBuilder str = new StringBuilder();
str.Append("<table class='isTable'><tr><th></th><th>用户名</th><th>webservices地址</th><th>webservices方法名称</th></tr>");
AppSettingsReader reader =
new AppSettingsReader();


NameValueCollection appStgs =
ConfigurationManager.AppSettings;

string[] names =
ConfigurationManager.AppSettings.AllKeys;

String value = String.Empty;

for (int i = 0; i < appStgs.Count; i++)
{


string key = names[i];
if (key.IndexOf("WebSiteUser") >= 0)
{
value = (String)reader.GetValue(key, value.GetType());
string[] strValue = value.Split(',');
string webservices = strValue[0];
string method = strValue[1];
str.Append("<tr><td><a style='color:White;text-decoration: none;' href=\"/sdmin/EditWebSiteUser?key=" + key + "\"><img src='../../Content/icons/admin_edit.png' alt='' title='编辑'/></a></td><td>" + key.Replace("WebSiteUser", "") + "</td><td>" + webservices + "</td><td>" + method + "</td></tr>");
}

}
str.Append("</table>");
ViewData["ListWebSiteUser"] = str;
return View();

Winform—C#读写config配置文件

现在FrameWork2.0以上使用的是:ConfigurationManager或WebConfigurationManager。并且AppSettings属性是只读的,并不支持修改属性值.

一、如何使用ConfigurationManager?

1、添加引用:添加System.configguration

在Winform中动态读写app.config文件在Winform中动态读写app.config文件在Winform中动态读写app.config文件

2、引用空间

在Winform中动态读写app.config文件

3、config配置文件配置节

常用配置节:

(1)普通配置节

<appSettings>  

  <add key="COM1" value="COM1,9600,8,None,1,已启用" />

</appSettings> 

(2)数据源配置节

<connectionStrings>
  <add name="kyd" connectionString="server=.;database=UFDATA_999_2017;user=sa;pwd=123"/>
</connectionStrings>

(3)自定义配置节

在Winform中动态读写app.config文件

 

 

二、config文件读写

1、依据连接串名字connectionName返回数据连接字符串  

//依据连接串名字connectionName返回数据连接字符串  
        public static string GetConnectionStringsConfig(string connectionName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            string connectionString =
                config.ConnectionStrings.ConnectionStrings[connectionName].ConnectionString.ToString();
            return connectionString;
        }

2、更新连接字符串  

///<summary> 
        ///更新连接字符串  
        ///</summary> 
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param> 
        public static void UpdateConnectionStringsConfig(string newName, string newConString, string newProviderName)
        {
            //指定config文件读取
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);

            bool exist = false; //记录该连接串是否已经存在  
            //如果要更改的连接串已经存在  
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            {
                exist = true;
            }
            // 如果连接串已存在,首先删除它  
            if (exist)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            //新建一个连接字符串实例  
            ConnectionStringSettings mySettings =
                new ConnectionStringSettings(newName, newConString, newProviderName);
            // 将新的连接串添加到配置文件中.  
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改  
            config.Save(ConfigurationSaveMode.Modified);
            // 强制重新载入配置文件的ConnectionStrings配置节  
            ConfigurationManager.RefreshSection("connectionStrings");
        }

3、返回*.exe.config文件中appSettings配置节的value项  

///<summary> 
        ///返回*.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        public static string GetAppConfig(string strKey)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == strKey)
                {
                    return config.AppSettings.Settings[strKey].Value.ToString();
                }
            }
            return null;
        }

4、在*.exe.config文件中appSettings配置节增加一对键值对  

///<summary>  
        ///在*.exe.config文件中appSettings配置节增加一对键值对  
        ///</summary>  
        ///<param name="newKey"></param>  
        ///<param name="newValue"></param>  
        public static void UpdateAppConfig(string newKey, string newValue)
        {
            string file = System.Windows.Forms.Application.ExecutablePath;
            Configuration config = ConfigurationManager.OpenExeConfiguration(file);
            bool exist = false;
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                if (key == newKey)
                {
                    exist = true;
                }
            }
            if (exist)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            config.AppSettings.Settings.Add(newKey, newValue);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }

5、修改IP地址

在Winform中动态读写app.config文件在Winform中动态读写app.config文件

// 修改system.serviceModel下所有服务终结点的IP地址
        public static void UpdateServiceModelConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["system.serviceModel"];
            ServiceModelSectionGroup serviceModelSectionGroup = sec as ServiceModelSectionGroup;
            ClientSection clientSection = serviceModelSectionGroup.Client;
            foreach (ChannelEndpointElement item in clientSection.Endpoints)
            {
                string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
                string address = item.Address.ToString();
                string replacement = string.Format("{0}", serverIP);
                address = Regex.Replace(address, pattern, replacement);
                item.Address = new Uri(address);
            }

            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("system.serviceModel");
        }

        // 修改applicationSettings中App.Properties.Settings中服务的IP地址
        public static void UpdateConfig(string configPath, string serverIP)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
            ConfigurationSectionGroup sec = config.SectionGroups["applicationSettings"];
            ConfigurationSection configSection = sec.Sections["DataService.Properties.Settings"];
            ClientSettingsSection clientSettingsSection = configSection as ClientSettingsSection;
            if (clientSettingsSection != null)
            {
                SettingElement element1 = clientSettingsSection.Settings.Get("DataService_SystemManagerWS_SystemManagerWS");
                if (element1 != null)
                {
                    clientSettingsSection.Settings.Remove(element1);
                    string oldValue = element1.Value.ValueXml.InnerXml;
                    element1.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element1);
                }

                SettingElement element2 = clientSettingsSection.Settings.Get("DataService_EquipManagerWS_EquipManagerWS");
                if (element2 != null)
                {
                    clientSettingsSection.Settings.Remove(element2);
                    string oldValue = element2.Value.ValueXml.InnerXml;
                    element2.Value.ValueXml.InnerXml = GetNewIP(oldValue, serverIP);
                    clientSettingsSection.Settings.Add(element2);
                }
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("applicationSettings");
        }

        private static string GetNewIP(string oldValue, string serverIP)
        {
            string pattern = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
            string replacement = string.Format("{0}", serverIP);
            string newvalue = Regex.Replace(oldValue, pattern, replacement);
            return newvalue;
        }
在Winform中动态读写app.config文件

修改IP地址

 

config 读写方法

using System.Configuration;
//省略其他代码
public SalesOrderData()
        {
            string str = "";
            str = ConfigurationManager.ConnectionStrings["kyd"].ToString();
            conn = new SqlConnection(str);
            cmd = conn.CreateCommand();
        }

 实际应用:

1、获取配置节的值

button1 点击获取配置节<appSettings>指定key的value值

button2 点击获取配置节<connectionStrings>指定name的connectionString值

在Winform中动态读写app.config文件

在Winform中动态读写app.config文件

在Winform中动态读写app.config文件

结果为:

在Winform中动态读写app.config文件

2、修改配置节的值

button1 点击获取配置节<appSettings>指定key的value值

button2 点击修改配置节<connectionStrings>指定key的value值为文本框的值

button3 点击获取配置节<appSettings>指定key新的value值

在Winform中动态读写app.config文件

在Winform中动态读写app.config文件

在Winform中动态读写app.config文件

结果为:

 在Winform中动态读写app.config文件

此时配置文件key1的value值为,获取key值仍为修改前的值

在Winform中动态读写app.config文件

如何重置为修改前的值?

在Winform中动态读写app.config文件

如何保存修改后的值?文章来源地址https://www.toymoban.com/news/detail-463885.html

到了这里,关于在Winform中动态读写app.config文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • android studio开发——android11版本以上权限动态申请问题,包括文件读写、图片、相机的调用

    用于android手机的升级,现在已经是android13版本了,对于权限问题可能更加敏感了,前段时间开发发现之前的方法已经不再适用于android11以后的版本了 读写权限申请最好是跳转到设置中进行才是最好了,下面我们开始进行 首先是AndroidManifest.xml文件的权限 然后这里讲解一下权

    2024年02月10日
    浏览(47)
  • C# App.config和Web.config加密

    使用ASP.NET提供的命令工具aspnet_regiis来创建加密命令。 这个命令将加密App.config文件中的connectionStrings设置。C:MyAppFolder是应用程序的根目录。  这个命令将会加密Web.config文件中的appSettings设置。   如果需要编辑加密的配置节,可以使用aspnet_regiis提供的解密命令。 这个命令将

    2024年02月14日
    浏览(19)
  • 开源云真机平台-Sonic平台-python自定义脚本-config.ini方式实现全局配置参数的读写操作

    config.ini方式实现全局配置参数的读写操作 使用python实现以下功能: 1、使用将接口获取的变量值,写入到当前目录下的config文件中,如delayTime=10; 2、读取当前目录下的config文件中,特定变量的值,如delayTime=10; 3、若config文件或者节点不存在,则自动进行创建; 实测,可以

    2024年01月17日
    浏览(33)
  • c# winform实现控件类型、数量的动态更新

    在系统开发的过程中,往往会遇到需要动态的控制控件内部显示的控件数量、控件类型的情况,比如这样的。 1、问题描述:如何自定义的控制控件中数据显示的类型呢? 首先面对这个问题,我们得先了解winform的控制工具中有哪些控件是可以用来承载其他控件工具的,例如以

    2024年02月16日
    浏览(30)
  • Vue3之app.config.globalProperties(定义全局变量)

    注意:如果全局属性与组件自己的属性冲突,组件自己的属性将具有更高的优先级。 1、创建一个文件(通过useGlobelProperties获取全局属性) 2、在main.ts中(配置全局属性) 3、任意组件中的使用 打印所得:   可以看到我们上面定义的name可以拿到,后续想要什么全局配置,可

    2024年02月15日
    浏览(27)
  • vue3.0全局变量app.config.globalProperties的使用

    app.config.globalProperties是一个用于注册能够被应用内所有组件实例访问到的全局属性的对象。是Vue2中Vue.prototype使用的一种替代,具体用法如下: 1、在组合式api使用: 2、在选项api中使用:

    2024年02月11日
    浏览(23)
  • 在WInform开发中实现工具栏/菜单的动态呈现

    在Winform系统开发中,为了对系统的工具栏/菜单进行动态的控制,我们对系统的工具栏/菜单进行动态配置,这样可以把系统的功能弹性发挥到极致。通过动态工具栏/菜单的配置方式,我们可以很容易的为系统新增所需的功能,通过权限分配的方式,可以更有效的管理系统的菜

    2024年02月04日
    浏览(39)
  • 前端笔记(4) Vue3 全局属性 app.config.globalProperties 使用案例

    学习Vue3有个把月了,记录下学习中的小知识点。 首先很多同学还没找到Vue3真正的官方文档,下面给出Vue3的文档网站 Vue3官网文档 Vue3API文档 官方解释:一个用于注册能够被应用内所有组件实例访问到的全局 property 的对象。 案例: 首先有一个请求后端接口的方法 在main.ts文

    2024年02月12日
    浏览(25)
  • Spring Cloud【Config客户端配置与测试、Config客户端之动态刷新 、什么是Spring Cloud Bus、Docker安装RabbitMQ】(十)

      目录 分布式配置中心_Config客户端配置与测试 为什么要引入bootstrap 

    2024年02月15日
    浏览(29)
  • MoveIt!生成的机器人**_moveit_config包中config文件和launch文件

    ros版本:noetic 官方教程地址MoveIt1 官方教程地址MoveIt2 安装MoveIt! 通过以下命令安装MoveI! follow_joint_trajectory 允许客户端向机器人控制器发送关节轨迹。 轨迹以关节位置、速度和加速度的列表形式指定,控制器将尝试尽可能精确地跟踪轨迹。 JointTrajectoryAction: 关节轨迹动作组,

    2024年02月04日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包