2009-12-02 42 views
10

Làm thế nào để đọc thông tin chuỗi kết nối từ tệp app.config sử dụng .net api?.net 3.5: Để đọc chuỗi kết nối từ app.config?

Platform là Net 3,5

 <?xml version="1.0" encoding="utf-8" ?> 
     <configuration> 
      <connectionStrings> 
       <add connectionString="" providerName="" name=""/> 
      </connectionStrings> 
     </configuration> 

Trả lời

13

Hãy xem Reading Connection Strings in Web.Config and App.Config and Enterprise Library DAAB Settings (trên Máy Wayback như bản gốc đã bị xóa)

ConnectionStringSettings connection = ConfigurationManager.ConnectionStrings["MyConnectionString"] 
string connectionString = connection.ConnectionString 

Bạn có thể cần thêm một tài liệu tham khảo lắp ráp để System.Configuration

+0

Tôi đã tìm kiếm xa và rộng và không thể tìm thấy liên kết được cập nhật cho hướng dẫn bạn tham khảo .. Bạn có xảy ra liên kết được cập nhật cho nó không? – ecoe

+0

@ecoe Tôi đã tìm thấy nó trên [Máy ​​Wayback] (http://web.archive.org/web/20120307192453/http://davidhayden.com/blog/dave/archive/2007/02/22/ReadConnectionStringsWebConfigAppConfig .aspx) – Justin

2

Nếu name là một giá trị chuỗi đại diện cho tên của chuỗi kết nối:

var connectionString = 
    ConfigurationManager.ConnectionStrings[name].ConnectionString; 

Trong ví dụ của bạn, bạn đã không cung cấp giá trị cho name , vì vậy bạn sẽ phải làm điều đó trước khi nó hoạt động.

4

Trong cấu hình:

<add name="ConnectionName" connectionString="Data Source=xxxx\yyyy;Initial Catalog=MyDB;User ID=userName;Password=pwd" /> 

Trong C# mã:

using System.Configuration; 

... 

    string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ToString(); 

Vẫn còn tốt hơn sẽ được xác định một chức năng và sử dụng nó trong các mã ở khắp mọi nơi:

public string getConnectionStringMyDB() 
     { 
      return ConfigurationManager.ConnectionStrings["ConnectionName"].ToString(); 
     } 
0

Đây là những gì tôi đã làm.

Tôi cần một dịch vụ để bắt đầu tự động và kết nối với cơ sở dữ liệu MS SQL như một phần của quá trình khởi động. Điều này có nghĩa là tên của chuỗi kết nối DB cần được lưu trữ trong sổ đăng ký và chuỗi được lưu trữ trong sổ đăng ký phải tương ứng với một chuỗi kết nối được xác định. Câu trả lời là một applet WinForm nhỏ quản lý việc lưu trữ đăng ký các tham số khởi động cho dịch vụ mà một trong các tham số storde là tên của chuỗi kết nối DB.

Tôi đã thêm hai hàm tĩnh vào lớp bối cảnh cơ sở dữ liệu do Linq tạo. Một phương pháp liệt kê các tên kết nối DB được định nghĩa trong phần cài đặt cho dự án DB. Phương thức thứ hai trả về cho tôi một bối cảnh DB từ tên kết nối DB cung cấp. Ứng dụng quản lý đăng ký được gọi là phương thức liệt kê để điền vào hộp danh sách và dịch vụ windows được gọi là phương thức GetDBContextFromConnectionName() để chuyển đổi tên kết nối DB được lấy ra từ sổ đăng ký vào một bối cảnh DB. ngữ cảnh DB sau đó được sử dụng để truy cập DB.

Hai phương pháp này được đưa vào một tệp lớp mà tôi đã thêm vào dự án có cùng tên với lớp dữ liệu được tạo bởi LINQ.

Kết quả là: ` bằng cách sử dụng Hệ thống; bằng System.Configuration; bằng System.Collections.Generic; bằng System.Collections;

namespace RepositoryProject 
{ 
    public partial class RepositoryDataContext 
    { 
     /// <summary> 
     /// Return a MS SQL-LINQ DB Context given the name of the DB Connection name defined in 
     /// Properties.Settings.Default area of the SQL-Linq project. 
     /// </summary> 
     /// <param name="dbConnectionName">The name of the prediefined DB Connection string</param> 
     /// <returns>A SQL-Linq database context </returns> 
     public static RepositoryDataContext GetDBContextFromConnectionName(string dbConnectionName) 
     { 
      string fullConnectionString = null; 

      dbConnectionName = dbConnectionName.Trim(); 
      if (!String.IsNullOrEmpty(dbConnectionName)) 
      { 
       SettingsPropertyCollection allConnectionStrings = global::Cognex.TA.Framework.Properties.Settings.Default.Properties; 
       SettingsProperty connectionProperty = allConnectionStrings[dbConnectionName]; 
       if (null != connectionProperty) 
       { 
        fullConnectionString = (string) connectionProperty.DefaultValue; 
        if (String.IsNullOrEmpty(dbConnectionName)) 
        { 
         string msg = ""; 
         msg += String.Format("The connection string name, {0}, exists within the settings of the RepositoryDataContext class but creates an empty DB connection string.", dbConnectionName); 
         throw new ArgumentException(msg); 
        } 
       } 
       else 
       { 
        string msg = ""; 
        msg += String.Format("The connection string name, {0}, does not exist within the settings of the RepositoryDataContext class.", dbConnectionName); 
        throw new ArgumentException(msg); 
       } 
      } 
      else 
      { 
       string msg = ""; 
       msg += "The connection string name to the test repository cannot be null or empty."; 
       throw new ArgumentException(msg); 
      } 

      return new RepositoryDataContext(fullConnectionString); 

     } 

     /// <summary> 
     /// Return a list of all the DB Connection names defined in 
     /// Properties.Settings.Default area of the SQL linq project. 
     /// </summary> 
     /// <returns>A list of DB Connection name</returns> 
     public static List<string> GetAllDBConnectionNames() 
     { 
      List<string> listONames = new List<string>(); 

      /* 
      * within the the Linq-generated code (TestRepository.designer.cs) there is an empty constructor for 
      * the data context which looks similar to this: 
      * 
      * public TestRepositoryDataContext() : 
      * base(global::Framework.Properties.Settings.Default.DefaultConnectionString, mappingSource) 
      * { 
        OnCreated(); 
      * } 
      * 
      * Duplicate that assembly name here 
      */ 
      SettingsPropertyCollection allConnectionStrings = global::Framework.Properties.Settings.Default.Properties; 
      foreach(SettingsProperty entry in allConnectionStrings) 
      { 
       if (entry.PropertyType.ToString().Equals("System.String")) 
       { 
        listONames.Add(entry.Name); 
       } 
      } 

      return listONames; 
     } 
    } 
} 

'

Tôi hy vọng điều này sẽ giúp.

Các vấn đề liên quan