【问题标题】:how to manipulate connectionstring in app.config file?如何在 app.config 文件中操作连接字符串?
【发布时间】:2017-04-18 06:50:54
【问题描述】:

我试图在运行时设置connectionstring。我需要的是在运行时设置datasource 并重新启动应用程序。我在 google 中找到了一些方法,但问题是 app.configApplication.Restart(); 之后返回默认值

我尝试将connectionstring 保存在settings.csapp.config 中,但这对我不起作用。 这是我的代码:

public void setConnectionString()
    {
        try
        {
            string str = string.Empty;

            str = string.Format(@"Data Source={0}; Initial Catalog=CRM01_DB; UID= {1}; PWD={2}", Default.DataSource, Default.UID, Default.UPass);

            this["CRM01_DBConnectionString"] = str;
            Default.Save();
            Thread.Sleep(100);
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
            connectionStringsSection.ConnectionStrings["CRM01_DBConnectionString"].ConnectionString = str;
            config.Save();
            ConfigurationManager.RefreshSection("connectionStrings");

            Thread.Sleep(100);

        }
        catch (System.Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }

我没有收到任何错误,但是当应用程序启动时 connectionstrig 具有默认值

【问题讨论】:

    标签: c# connection-string app-config application-settings


    【解决方案1】:

    如果您从 VS 测试此代码,它可能无法工作(也可能不会)。

    从 VS 运行时,实际执行的程序是 <your_program>.vshost.exe,对应的 .config 文件名为 <your_program>.vshost.exe.config,您应该在那里检查您的更改。

    但是..

    VS 保持原始 .config.vshost.exe.config 同步,这样您就看不到您的更改。

    要测试代码是否有效,请在 VS 外部尝试或取消选中 Enabled the Visual Studio hosting process (Properties -> Debug)(记住它有 implications

    【讨论】:

    • @mohammadboluki 我试过了。像魅力一样工作
    猜你喜欢
    • 2013-02-01
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    相关资源
    最近更新 更多