嗨目前我试图测试更改配置文件失效,测试引发的事件由FileSystemWatcher的
我用下面的代码来做到这一点...
string path = _pathInvalidFormat.Substring(0, _pathInvalidFormat.LastIndexOf('\\'));
System.IO.File.Copy("TestInvalidXmlConfigurationFile.xml", _pathInvalidFormat, true);
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path);
//catch the invalid file getting deleted
fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted);
//catch the temporary config file getting renamed
fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed);
fileSystemWatcher.EnableRaisingEvents = true;
CreateConfig(_pathInvalidFormat);
System.Threading.Thread.Sleep(5000);
Assert.That(_oldFileDeleted);
Assert.That(_newFileCreated);
ResetConfig(_pathInvalidFormat);
不过我不满意这个使用System.Threading.Thread.Sleep(5000);
我试过使用fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Deleted,5000);但似乎无法使其发挥作用,因为它似乎总是达到暂停。即使我看到已删除的事件已被击中,它仍然不会返回。
或者有更好的方式让系统等待异步事件被触发?
感谢
基兰
- 编辑:
我用createconfig(路径)使用下面的方法
private void ReadConfiguration(string path)
{
var configFileMap = new ExeConfigurationFileMap()
{
ExeConfigFilename = path,
};
// if we try to read bad formatted file let's
// 1. delete this file
// 2. call read configuration to form correct file
try
{
Config = System.Configuration.ConfigurationManager
.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
}
catch (ConfigurationErrorsException)
{
// ok, there is bad format file, let delete it and create another one
// TODO: check security rights?
File.Delete(path);
ReadConfiguration(path);
}
}
希望创建一个系统配置文件这给了一些见解至于我的测试试图达到什么目的。
'CreateConfig'是否单独进行线程化?第一个建议是阻止它,除非另有需要。 – 2012-04-26 11:34:39
该方法本身不在单独的线程中,如果有帮助,我添加了CreateConfig调用的代码。 – Kezza 2012-04-26 11:49:01
我假设filewatcher在不同的线程上运行,但是事件异步引发。 – Kezza 2012-04-26 11:52:19