I have looked at multiple SO questions related to mine, as well as Googling, and I have been unable to find a solution that works for me.
Given a list of files, I am trying to cull all the non-cs ones, for reasons. I take the string array, convert to list, and iterate over the list, removing all the files I don't want by using list.Remove().
After the first removal, it errors out with
Collection was modified; enumeration operation might not execute
The code is:
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
//Converting to list, to use list.Remove rather than rewriting entire array at each delete
var list = new List<string>(files);
foreach (string readFile in list)
{
if (Path.GetExtension(readFile) != ".cs") //|| Path.GetExtension(readFile) != ".dll")
{
//remove, as we don't currently care about non cs files.
list.Remove(readFile);
}
}
//Converting back to string array for use in the rest of the program
files = list.ToArray();
}
I have also tried RemoteAt(), which produces the same error.
string[] files = null;
try
{
files = System.IO.Directory.GetFiles(currentDir);
//Converting to list, to use list.Remove rather than rewriting entire array at each delete
var list = new List<string>(files);
int i = 0;
for(int i=0; i<list.Count();i++)
{
if (Path.GetExtension(readFile) != ".cs") //|| Path.GetExtension(readFile) != ".dll")
{
//remove, as we don't currently care about non cs files.
list.RemoveAt(i);
}
i++;
}
//Converting back to string array for use in the rest of the program
files = list.ToArray();
}
Any recommendations for overcoming this error, as some of the directories will have over 500 files in them, and I want to avoid rewriting the string array as much as possible.
I have read the following SO questions:
How to remove item from list in C#?
C# error Collection was modified; enumeration operation might not execute