C# 从 App.config 文件中定义的连接字符串中获取服务器名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15319213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:24:57  来源:igfitidea点击:

Get the Server Name from Connection string Defined in App.config File?

c#connection-string

提问by ozzy_mra

I want to get IP Adress of ConnectionString's serverName from my app.config file and then ping it. Actually i want ping my server before running my application. how do i do this? my ConnectionString

我想从我的 app.config 文件中获取 ConnectionString 的 serverName 的 IP 地址,然后 ping 它。实际上我想在运行我的应用程序之前 ping 我的服务器。我该怎么做呢?我的连接字符串

<"name="ConnectionString"
 connectionString="Data Source=192.168.1.5;
                   Initial Catalog=CheckPass2;
                   User ID=User;
                   Password=myPassword" />

采纳答案by Bhushan Firake

How do I do this?

我该怎么做呢?

You can get the server address using SqlConnectionStringBuilder.The DataSourceproperty of this class can be used for this as below:

您可以使用SqlConnectionStringBuilder获取服务器地址。DataSource该类的属性可用于此目的,如下所示:

// Retrieve the ConnectionString from App.config 
string connectString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
// Retrieve the DataSource property.    
string IPAddress = builder.DataSource;

This DataSourceproperty corresponds to the following keys within the connection string.

DataSource属性对应于连接字符串中的以下键。

  • Data Source
  • server
  • address
  • addr and
  • network address
  • 数据源
  • 服务器
  • 地址
  • 地址和
  • 网络地址

Regardless of which of these values has been supplied within the supplied connection string, the connection string created by the SqlConnectionStringBuilderwill use the well-known "Data Source"key.

无论在所提供的连接字符串中提供了这些值中的哪一个,由 所创建的连接字符串SqlConnectionStringBuilder都将使用众所周知的"Data Source"键。