c# - 在 Windows 窗体应用程序中处理连接字符串的最佳方法是什么?

标签 c# sql-server app-config

我的 C# 应用程序使用 DataSetTableAdapters。它们是从 VS2008 GUI 工具生成的。

例子:

Right click project - > Add New Item - > DataSet

此方法自动将连接字符串添加到app.config

但这是连接字符串的硬编码方法。我想以一种简单的方式更改连接字符串。但是当我使用数据集时,连接字符串从应用程序属性中获取。 这种情况有什么解决办法吗?

enter image description here

这是我在 Settings.Designer.cs 文件中存储的连接字符串

    namespace WindowsFormsApplication2.Properties {


    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }

        [global::System.Configuration.ApplicationScopedSettingAttribute()]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
        [global::System.Configuration.DefaultSettingValueAttribute("Data Source=SLCERT\\SQLEMK;Initial Catalog=TestDataBase;Integrated Security=True")]
        public string TestDataBaseConnectionString {
            get {
                return ((string)(this["TestDataBaseConnectionString"])); // this is the connection string get from the dataset's
            }
        }
    }
}

app.config 包含

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="WindowsFormsApplication2.Properties.Settings.TestDataBaseConnectionString"
            connectionString="Data Source=SLCERT\SQLEMK;Initial Catalog=TestDataBase;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

最佳答案

我相信您会问这个问题,这样您就不必在本地测试和生产/测试服务器之间手动切换。

您可能想看看 How to: Transform Web.config When Deploying a Web Application Project

它是关于 web.config 而不是 app.config 但它是相同的想法。

附言。仅适用于 VS 2010 及以上版本

关于c# - 在 Windows 窗体应用程序中处理连接字符串的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15610374/

相关文章:

c# - PayU 集成网络服务 URL

mysql - SQL 查询 我开始使用 MySQL 而不是 SQL Server

sql - 可序列化事务是如何实现的?

c# - 依赖注入(inject)不适用于 IConfiguration C#.Net Core

c# - 如何使用 LINQ 从表中获取最新条目?

c# - 为什么我得到 "The name x does not exist in the current context"?

c# - Web.Config,system.serviceModel 的外部文件

.net - 如何将配置文件引入 Powershell 脚本?

c# - WPF DataTrigger for TextBlock 控制Text

c# - 从表中删除行而不先检查它们是否存在