【问题标题】:Getting the connection string in a c# service在 C# 服务中获取连接字符串
【发布时间】:2012-03-07 06:48:24
【问题描述】:

我正在使用 VS 2008。

我有一个需要部署的服务。该服务不会在 .NET 客户端(如网站或 Windows 客户端)中使用。它需要一个数据库连接。

我最初有一个调用服务的控制台应用程序,连接字符串是在控制台应用程序的 app.config 中设置的。我想将连接字符串移动到服务。因此,在服务附带的 web.config 中,我输入了以下内容:

<connectionStrings>

     <clear />
     <add name="REConnectionString"
          connectionString="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"
          providerName="System.Data.SqlClient" />

</connectionStrings>

在我的 MyService.svc.cs 我有以下内容:

private readonly string connectionString = ConfigurationManager.ConnectionStrings["REConnectionString"].ConnectionString;

但是当我运行服务时,这个值 connectionString 是空的。如何从 web.config 中获取此值?

我什至添加了以下内容,但它也不起作用:

<appSettings>
     <add key="REConnectionString" value="Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=True;"/>
</appSettings>

如果我遍历连接字符串列表,那么它会继续从调用应用程序中取回连接字符串。配置文件没有办法用吗?

【问题讨论】:

  • 尝试调试并查看 ConfigurationManager.ConnectionStrings 中的内容...看来您的代码可能有效。
  • 还有这个,也许他们可以帮助你stackoverflow.com/questions/9494699/…
  • 如果循环访问ConfigurationManager.ConnectionStrings 会发生什么?也许您的应用使用的配置文件与您正在查看的不同?
  • @Jeroen:我遍历了连接字符串,它仍然从调用应用程序返回连接字符串。我不想要它,因为调用应用程序将是一个 Java 应用程序。我想在服务或我的数据层中设置连接字符串。

标签: c# .net wcf web-services connection-string


【解决方案1】:

我会尝试这样的:

Configuration config = ConfigurationManager.OpenExeConfiguration("name_of_your_service.exe");
string connectString = config.ConnectionStrings["YourConnectionStringNameHere"];

您应该注意作为配置文件名称传递的字符串。
它应该是 exe 或 dll 的名称,而不是配置文件本身。 OpenExeConfiguration 将作为配置对象打开一个名为“name_of_your_service.exe.config”的文件

OpenExeConfiguration的详细信息

刚刚发现一个有趣的问题here on SO

【讨论】:

    【解决方案2】:

    我右键单击该项目并添加了类型连接字符串的设置。然后我像这样检索它:

    MyProject.Properties.Settings.Default.MyConnectionString;
    
    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2018-12-18
    • 2018-11-18
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多