3

app.configに次のような接続文字列があります

<add name="CONN" connectionString="SERVER=SERVER\SQLEXPRESS;DATABASE=TRIAL_LINK;uid=sa;pwd=trial"
        providerName="System.Data.SqlClient" />

DBLinkerというフォームがあり、他のサーバーとデータベースを選択するオプションをユーザーに提供しています。たとえば、サーバー名を「MAILSERVER」、データベースを「Actual」として選択しています。次のコードを使用してapp.configファイルを上書きしています。

Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

Dim mySection As ConnectionStringsSection = DirectCast(config.GetSection("CONN"),ConnectionStringsSection)
Dim conStr As String = "SERVER=MAILSERVER;DATABASE=Actual;uid=sa;pwd=trial"

config.ConnectionStrings.ConnectionStrings("CONN").ConnectionString = conStr
config.Save(ConfigurationSaveMode.Full)


ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name)

このコードの後、アプリケーションのログインフォームを開こうとしています。しかし、ここで接続文字列にアクセスしようとすると、更新された文字列ではなく、以前の文字列をフェッチしています。

4

2 に答える 2

2

プログラムでweb.config設定を上書きする方法

実行時にweb.configを変更して、アプリケーションの実行中に有効にすることはできないようです。これを回避するには、設定を文字列のベース部分にしてから、ユーザー選択を使用して残りを作成します。新しい文字列はいつでもSession、cookie、またはDbに保存して、必要に応じて必要なときに手元に置いておくことができます。

お役に立てれば。

于 2012-10-17T07:14:57.870 に答える
1
 Public Sub updateConfigFile(ByVal con As String)
        'updating config file
        Dim XmlDoc As New XmlDocument()
        'Loading the Config file
        XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
        For Each xElement As XmlElement In XmlDoc.DocumentElement
            If xElement.Name = "connectionStrings" Then
                'setting the coonection string
                xElement.FirstChild.Attributes(2).Value = con
            End If
        Next
        'writing the connection string in config file
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
    End Sub

このコードを使用して、この問題を解決しました。

于 2012-10-19T10:56:15.040 に答える