この「動作していません」という他の投稿がありますが、実行中にConfigurationManagerを再起動して3日かけてリスタートするのは嫌ですサービス、私はどこにも回っていない。app.configリフレッシュセクションでappsettingsセクションをリロードしていない
私はこのブログの記事を使用している:
http://dejanstojanovic.net/aspnet/2015/june/auto-realod-application-config-in-net/
は、そのファイルが保存されている部分を再ロードfilewatcherを作成する際に、私を支援します。
ファイル変更時にappSettingsセクションを更新するように変更しました(下記のコードを参照)。しかし、どのような方法で試しても、セクションをリフレッシュせず、起動時に存在する値が出てくるだけです。
私が試してみました:
- を外部プロジェクトからのモニターのクラスを移動、それはクロスドメイン保護事業のいくつかの並べ替えなどに干渉されている波平ことを確認するために、同じコードベース/プロジェクトに。
- 別のセクションをapp.configに追加して再ロードして、
appSettings
セクションを保護することに基づくいくつかの.netセキュリティを保証していないことを確認してください。 - 名前変更
appSettings
どのようにしても、名前付けの問題ではないことを確認できます(どこでも読み取るrefreshsection(..)
は大文字と小文字が区別されます)。
ここにいる誰かが、私がそのような馬鹿になっているところを指し示してくれることを願っています。
コード:
public class ConfigMonitor
{
private readonly FileSystemWatcher _watcher;
private DateTime _lastChange;
public ConfigMonitor(string configFilePath)
{
if (configFilePath == null)
{
throw new ArgumentNullException(nameof(configFilePath));
}
_lastChange = DateTime.MinValue;
configFilePath = string.Concat(System.Reflection.Assembly.GetEntryAssembly().Location, ".config");
if (File.Exists(configFilePath))
{
_watcher = new FileSystemWatcher(Path.GetDirectoryName(configFilePath), Path.GetFileName(configFilePath))
{
EnableRaisingEvents = true
};
_watcher.Changed += Watcher_Changed;
}
}
~ConfigMonitor()
{
_watcher.EnableRaisingEvents = false;
_watcher.Changed -= Watcher_Changed;
_watcher.Dispose();
}
public void Stop()
{
_watcher.EnableRaisingEvents = false;
_watcher.Changed -= Watcher_Changed;
_watcher.Dispose();
}
private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
if ((DateTime.Now - _lastChange).Seconds <= 5 || IsFileLocked(e.FullPath)) return;
var monitoredSections = ConfigurationManager.AppSettings["monitoredSections"];
if (monitoredSections != null)
{
IEnumerable<string> sections = monitoredSections.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (sections.Any())
{
foreach (var section in sections)
{
ConfigurationManager.RefreshSection(section);
}
}
}
else
{
Debug.WriteLine(ConfigurationManager.AppSettings["TEST"]);
ConfigurationManager.RefreshSection("appSettings");
Debug.WriteLine(ConfigurationManager.AppSettings["TEST"]);
}
_lastChange = DateTime.Now;
}
private bool IsFileLocked(string filePath)
{
FileStream stream = null;
try
{
stream = File.OpenRead(filePath);
}
catch (IOException)
{
return true;
}
finally
{
stream?.Close();
}
return false;
}
}
あなたの 'Debug.WriteLine'テストは実行されますか? – caesay
@caesay、yeh 'writelines'が出て、同じ値を表示するだけです(起動時にロードされた/起動時にロードされた) –