在 C# 应用程序中添加数据库服务器信息

Adding database server information in C# application

我在我的 C# 应用程序中使用以下连接字符串与本地托管的数据库通信。

string conn = String.Format("Server={0};Port={1};" +
                                "User Id={2};Password={3};Database={4};",
                                "localhost", "5432", "postgres",
                                "postgres", "table");
NpgsqlConnection connection = new NpgsqlConnection(connstring);
connection.Open();
NpgsqlCommand sqlcmd = new NpgsqlCommand("SELECT * FROM public.roads", connection);
NpgsqlDataReader r = sqlcmd.ExecuteReader();

有没有办法可以在 config.app 文件中添加服务器信息并在我的代码中访问它?

查看 Connection Strings and Configuration Files

在app/web.config:

<configuration>
  <configSections>
  (...)
  <connectionStrings>
    <add name="Name1" connectionString="..." />
  </connectionStrings>

代码中:

var connectionString = ConfigurationManager.ConnectionStrings["Name1"].ConnectionString;

请注意,使用 connectionStrings 部分而不是 appSettings 的好处是,如果您使用的是对象关系映射框架,则可能支持使用连接字符串姓名。

例如

public class RepositoryContext: DbContext
{
    public RepositoryContext() : base("Name1") 
    {
        (...)
    }