Click to See Complete Forum and Search --> : Compare file Names to string and delete files that don't match


JakeyCakes
February 23rd, 2006, 03:39 AM
Hi,

I need to compare file names(regardless of their extensions) with strings and delete those files where the names don't match. Any ideas?

Shuja Ali
February 23rd, 2006, 03:57 AM
Hi,

I need to compare file names(regardless of their extensions) with strings and delete those files where the names don't match. Any ideas?
Here is an easy way of doing it. Use the System.IO namespace. Get all the files matching the specific pattern using GetFiles method of Directory class and then loop through the Values returned and delete the files.string[] Files = System.IO.Directory.GetFiles(@"C:\","SearchPattern.*");
foreach (string fileName in Files)
System.IO.File.Delete(fileName);

JakeyCakes
February 23rd, 2006, 04:09 AM
Could this be used more specifically e.g.

a) be case insensitive and

b)

keep files called

IB01
IB04
IB06
IB07
IB08
SA01

and delete files that do not have the above names?

torrud
February 23rd, 2006, 04:49 AM
Well, to make a case insensitive search use the String.ToLower() or String.ToUpper() methods. But the filesystem is caseinsensitive by default, so you do not have to make anything by yourself.

Additional you can use the solution from Shuja Ali. You only have to invert to result. That you can easy by adding all filenames to an arraylist and after that you remove all filenames that was found by the searchpattern. All filenames remaining in the arraylist you can delete.

That's it, very simple. ;)

JakeyCakes
February 23rd, 2006, 05:13 AM
Thanks.

Shuja Ali
February 23rd, 2006, 05:21 AM
be case insensitive As already said, the filesystem itself is case-insensitive and the GetFiles function is also case-insensitive.
keep files called

IB01
IB04
IB06
IB07
IB08
SA01

and delete files that do not have the above names? You can do it by going through the array and checking if the filenames match. Somewhat similar to this //get all the files in the directory
string[] Files = System.IO.Directory.GetFiles(@"C:\Temp1","*.*");
//array of filenames that are not to be deleted
string[] checkPattern = new string[5] {"IB01", "IB06", "IB07", "IB08", "SA01"};
bool fileMatch = false;
//loop through all the files
foreach (string fileName in Files)
{
fileMatch = false;
//check if the filename matches the files that are not to be deleted
foreach (string temp in checkPattern)
{
if (fileName.IndexOf(temp) > 0)
{
fileMatch = true;
break;
}
}
//if there was no match then delete the file
if (!fileMatch)
System.IO.File.Delete(fileName);}