2014-02-24 53 views

回答

1

可以得到config文件中定義的連接字符串列表中使用System.Configuration.ConfigurationManager.ConnectionString屬性:

// Get the ConnectionStrings section.   
// This function uses the ConnectionStrings 
// property to read the connectionStrings 
// configuration section. 
public static void ReadConnectionStrings() 
{ 

    // Get the ConnectionStrings collection. 
    ConnectionStringSettingsCollection connections = 
     ConfigurationManager.ConnectionStrings; 

    if (connections.Count != 0) 
    { 
    Console.WriteLine(); 
    Console.WriteLine("Using ConnectionStrings property."); 
    Console.WriteLine("Connection strings:"); 

    // Get the collection elements. 
    foreach (ConnectionStringSettings connection in 
     connections) 
    { 
     string name = connection.Name; 
     string provider = connection.ProviderName; 
     string connectionString = connection.ConnectionString; 

     Console.WriteLine("Name:    {0}", 
     name); 
     Console.WriteLine("Connection string: {0}", 
     connectionString); 
    Console.WriteLine("Provider:   {0}", 
     provider); 
    } 
    } 
    else 
    { 
    Console.WriteLine(); 
    Console.WriteLine("No connection string is defined."); 
    Console.WriteLine(); 
    } 
} 

記得添加引用System.Configuration組裝。

相關問題