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

标签 c# connection-string

<分区>

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

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

最佳答案

How do I do this?

您可以使用 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;

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

  • 数据源
  • 服务器
  • 地址
  • 地址和
  • 网络地址

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

关于c# - 从 App.config 文件中定义的连接字符串获取服务器名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15319213/

相关文章:

c# - C# 中的只读列表

c# - 在当前打开的应用程序顶部显示隐藏的窗口窗体

c# - Entity Framework 如何处理事务?

c# - 带线程的 CoreAudioApi - InvalidCastException

ms-access - Access 数据库的只读连接字符串

c# - Entity Framework 在运行时更改连接

.net - 使用 Entity Framework 连接到 Oracle 时如何通过连接字符串更改架构?

sql-server - ASP.NET MVC 中出现 "The network path was not found"的原因

c# - 如何等待 MailMessage.SendAsync?

c# - 如何在c#中隐藏数据库连接的connectionString