I am getting list of my files in a directory and print their names on console, meanwhile i am adding a new file to the directory(Directory is monitored by FileSystemWatcher) to print its name, But it throws an exception: Collection was modified; Enumeration operation may not be executed..
This is the code:
private static void Main(string[] args)
    {
        var myfiles = new List<string>();
        myfiles = Directory.GetFiles(@"c:\items").ToList();
        foreach (var file in myfiles)
        {
            Console.WriteLine(file);
        }
    }
    public static void Run(List<string> myfiles)
    {
        var watcher = new FileSystemWatcher { Path = @"c:\items" };
        watcher.Created += (source, e) =>
        {
            myfiles.Add(e.FullPath);
        };
        watcher.EnableRaisingEvents = true;
    }
Q: How can i add item to list using Watcher while i am iterating through the list? is there any other way to add item to list in RealTime while iterating?
Note: In debugging i saw the Watcher will add the item to list properly, But after the item was added it throws an Exception.
Note: I also created a 2nd thread and put the Watcher in it.
 
    