如何通过asp.net mvc4中的webconfig获取数据库名称列表

时间:2014-02-24 11:33:37

标签: asp.net-mvc-3 asp.net-mvc-4

我在登录界面有一个组合框。在那个组合框中我需要数据库的名称。我该怎么做?请帮忙

1 个答案:

答案 0 :(得分:1)

您可以使用System.Configuration.ConfigurationManager.ConnectionString属性

获取.config文件中定义的连接字符串列表
// 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程序集的引用。