2010年9月14日 星期二

在程式中變更ConnectionString

通常使用Membership這類物件時,會建立web.config or app.config來設定連線字串及MembershipProvider
以下範例可以動態的在程式碼中變更資料庫連線字串


private void SetProviderConnectionString(string connectionString)
{
// Set private property of Membership, Role and Profile providers.
//Do not try this at home!!
FieldInfo connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);

if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);

FieldInfo roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);

if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);

FieldInfo profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);

if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
}

沒有留言:

張貼留言