简体   繁体   中英

How to create a connection string outside web.config

仅考虑这一点,是否可以在ASP.NET的web.config外部创建连接字符串?

您可能正在寻找configSource吗?

Yes you can store it anywhere it is just text.... The web.config is just a XML document that stores configuration settings about your application. You could just as easily create another XML file or a text file and read it in from there. You just wouldnt be able to use:

ConfigurationManager.ConnectionStrings[].ConnectionString 

You can create a connection string through the usage of .udl file.

UDL File Creation :

  1. Right-click on the desktop, or in the folder where you want to create the file.
  2. Select New, then Text Document.
  3. Give the Text Document any name with a .udl extension ("Show file extensions" must be enabled in folder options).
  4. A window will pop up warning that "If you change a filename extension, the file may become unusable. Are you sure you want to change it?" Select Yes.
  5. You have now successfully created a UDL file.

Now you need to implement the settings inside the .udl file according to your requirements. A video tutorial has been provided to explain you the whole procedure of using .udl file to create a connection string for MS SQL Server.

http://visiontechno.net/studymats/udlcreation.html

You can use following in case of MSSQL server

string connectionString = "Your Connection string"  

using (SqlConnection con = new SqlConnection(connectionString))
{
    //
    // Open the SqlConnection.
    //
    con.Open();
    //
    // The following code uses an SqlCommand based on the SqlConnection.
    //
    using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
    using (SqlDataReader reader = command.ExecuteReader())
    {
    while (reader.Read())
    {
        Console.WriteLine("{0} {1} {2}",
        reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
    }
    }
}

You can have it in another .config file that gets pulled in by your web.config like this:

<appSettings file="../Support/config/WebEnvironment.config">
</appSettings>

You can then use it in your code like this:

System.Configuration.ConfigurationManager.AppSettings["DefaultConnection"]

We have it such that this file isn't physically under our site, but it is virtually under it. That is the "Support" directory above is a virtual directory. Details can be found HERE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM