Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

asp.net - How to retrieve the databaseName and the serverName from the connectionstring in the webconfig?

How Do I get the connection string from the Web Config? I want to Display the database and the server name on to my master ASP.net page(C#).

The connection string in my web.config looks:

<add name="Application_ConnectionString" connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's also the SqlConnectionStringBuilder class:

var connectionString = 
  new System.Data.SqlClient.SqlConnectionStringBuilder("Data Source=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;Connection Timeout =60;Integrated Security=SSPI"); 

Console.WriteLine(connectionString.DataSource);
Console.WriteLine(connectionString.InitialCatalog);
// ...

Response to comment:

To get the connection strings directly from configuration, use:

foreach (ConnectionStringSettings c in System.Web.Configuration.WebConfigurationManager.ConnectionStrings)
{
    var connectionString = new SqlConnectionStringBuilder(c.ConnectionString)
    //connectionString.DataSource; // server name
    //connectionString.InitialCatalog; // database name
}

Note that this will include connection strings in your machine.config (e.g. data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true). If you don't want to see that you can filter it in code or add a <clear /> element to your web.config before your connection strings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...