2012-01-10 30 views
0

app.configファイルを使用して、いくつかのパラメータ(SQL Serverインスタンス名、ユーザー、パスワード、ログディレクトリなど)を保存して読み込みます。さて、私はbin/releaseディレクトリから.exeを実行する場合に限り、ユーザーに依存してこれを管理するいくつかのパラメータを変更する必要があります。 セットアップを作成してアプリケーションをインストールすると、このパラメータを変更できません - TargetInvocationExceptionがスローされます。私は管理者としてアプリを実行しようとしましたが、成功しませんでした。実行時にapp.configを変更すると例外が発生する

私が現在使用しているコードは以下の通りです:

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
config.AppSettings.Settings.Remove("username"); 
config.AppSettings.Settings.Add("username", this.Config.Username); 
config.Save(ConfigurationSaveMode.Modified); 
ConfigurationManager.RefreshSection("appSettings"); 

私はstackoverflowのではなく、成功せずに見つかったいくつかの他のソリューションを試してみた...

+0

このコードを実行すると、this.Config.Usernameの値は何ですか? – MethodMan

+1

これはかなり古典的なUACトラップです。開発マシンでプログラムをデバッグするときにファイルを変更できますが、インストール後は機能しません。 'c:\ program files'のファイルは書き込み可能ではありません。ファイルを編集する別のプログラムが必要になりますので、UACの高度を尋ねることができます。または、この情報を保存するための設定を使用しないでください。AppDataの.xmlファイルも機能します。 –

+0

@DJKRAZEのユーザー名の値が有効です。読むことができます。 – davor

答えて

0

この

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
KeyValueConfigurationCollection settings = config.AppSettings.Settings; 
// update SaveBeforeExit 
settings[username].Value = "newkeyvalue"; //how are you getting this.Config.Username 
    ... 
//save the file 
config.Save(ConfigurationSaveMode.Modified); 
//relaod the section you modified 
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 
のようなものを試してみてください

ここにいくつかの手順があります。たとえば、DateTimeの値に基づいて設定を変更したい場合などです。この簡単な説明は、あなたが簡単に従うべきです。

1: // Open App.Config of executable 
2: System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
3: // Add an Application Setting. 
4: config.AppSettings.Settings.Remove("LastDateChecked"); 
5: config.AppSettings.Settings.Add("LastDateChecked", DateTime.Now.ToShortDateString()); 
6: // Save the configuration file. 
7: config.Save(ConfigurationSaveMode.Modified); 
8: // Force a reload of a changed section. 
9: ConfigurationManager.RefreshSection("appSettings"); 
0

アプリケーションの実行中に設定エントリを変更することはできません。

binからexeを実行したときに、* .exe.configは変更されませんでした。

代わりに* .vshost.exe.Configファイルを変更しました。

System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); returns reference to *.vshost.exe.Config file 

* .exe.configは読み取り専用です。このファイルは更新できません。

関連する問題