While working on a project today I ran into this odd behavior in .NET.
I’m grabbing a list of file names and adding them to an object. However I need to filter the incoming names against a known list of “bad” names which led me to do this. (I’m by no means an advanced C# coder, still just learning it.) However, because it causes the aspnet_wp.exe process to run at 100% indefinitely, I assume that I’m doing something wrong with the language.
Here’s my code for reference:
List<string> localFiles = new List<string>();
// I was worried the object was causing the issue so dumbed it down to this with no changed.
string path = "//<file share>/<dir>/";
// As I commented below yes, it's slow when it works but it's clearly not working when using the if();
List<string> omitNames = new List<string>();
omitNames.Add("Thumbs.db");
// This is the only item in the list when it breaks also.
FileInfo[] localFileList = new DirectoryInfo(path).GetFiles();
foreach ( FileInfo item in localFileList )
{
if(!omitNames.Contains(item.Name))
{
localFiles.Add(path + itemName);
}
}
Can anyone explain why this code runs as an infinite loop? It looks like it really shouldn’t. Also, I realize that using a List may not be the best approach. Is there another way to implement this cleanly?
Commenting out the if(!){} for omitNames allows the code to run properly. (Though obviously the results are not filtered.)
UPDATE: It was requested to put this in a console app which you’ll find below. However it works perfectly. Another thing is that someone suggested that I try to simply compare it against a string. But the exact same thing happens if it’s changed to this:
if(item.Name != "Thumbs.db")
{
localFiles.Add(path + itemName);
}
Console App (which works):
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoopKiller
{
class Program
{
static void Main(string[] args)
{
List<string> omitNames = new List<string>();
List<string> localFiles = new List<string>();
omitNames.Add("Thumbs.db");
FileInfo[] localFileList = new DirectoryInfo("c:/test/").GetFiles();
foreach (FileInfo item in localFileList)
{
if (!omitNames.Contains(item.Name))
{
Console.WriteLine("Adding " + item.Name + " to localFiles.");
localFiles.Add(item.Name);
Console.WriteLine("Item added to localFiles.");
}
}
foreach (string item in localFiles)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
Is this any quicker?