Search code examples
c#.neteventsfilesystemwatcher

testing for raised events by FileSystemWatcher


Hi I am currently trying to test failure of a change to the config file,

I use the following code to do this...

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);

However I am not happy with this use of System.Threading.Thread.Sleep(5000);

I have tried using fileSystemWatcher.WaitForChanged(WatcherChangeTypes.Deleted, 5000); but cant seem to get it to work, as it always just seems to reach the timeout. Even when I can see the Deleted event has been hit, it still doesn't return.

Alternatively is there a better way of getting the system to wait for asynchronous events to be fired?

Thanks

Kieran

-- edited:

I use createconfig(path) to create a system config file using the following method

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);
    }
}

Hope this gives some insight as to what exactly my test is trying to achieve.


Solution

  • Put all the code in a function and execute it asynchronous with thread.

    Now, you can use manual reset events of threading to execute further code after sleep when file has been deleted, renamed and invalid path error checked.

    In this manner, code execution will be not blocked.

    refer this link for example