blah blah blah is here! blah blah » Close

up0down
link

hello,
i have this code

DirectoryInfo di = new DirectoryInfo(Application.StartupPath + "\\lab"); // or whatever it's called
FileInfo[] fia = di.GetFiles();
DirectoryInfo[] subDirs = di.GetDirectories();
string[] excluded = { "10.bmp", "New Folder1"};
foreach (DirectoryInfo subDir in subDirs)
foreach (FileInfo fi in fia)
{
if (fi.Name == excluded[0] || fi.Name == excluded[1] ) continue;
try
{
fi.Delete();

subDir.Delete(true);
}
catch
{
//
}
}
subDirs = null;


this code wile delete all files and folders except the files i want (10.bmp)

but the problem is i can exclude files but i can't exclude Folders (New Folder1)


can someone HELP ME.

last answered one year ago

2 answers

link

You have nested foreach loops so it won't behave as you had intended. You should iterate through all the files then iterate through all the folders in separate loops.

i.e.,

var path = Application.StartupPath + "\\lab";
var di = new DirectoryInfo(path);
var dirs = di.GetDirectories();
var files = di.GetFiles();
var exclusions = new string[] { @"10.bmp", @"New Folder1" };
foreach (var dir in dirs)
{
bool dirIsExcluded = false;
foreach (var exclude in exclusions) //see if dir is excluded
{
if (exclude.Equals(dir.Name, StringComparison.InvariantCultureIgnoreCase))
{
dirIsExcluded = true;
break;
}
}
if (!dirIsExcluded)
{
//do stuff
}
}
foreach (var file in files)
{
bool fileIsExcluded = false;
foreach (var exclude in exclusions) //see if dir is excluded
{
if (exclude.Equals(file.Name, StringComparison.InvariantCultureIgnoreCase))
{
fileIsExcluded = true;
break;
}
}
if (!fileIsExcluded)
{
//do stuff
}
}

king_888
153

thank you Jeff1203

up1down
link

in line

foreach (DirectoryInfo subDir in subDirs)


you have to add other test for exclusion as you have for file:
if (fi.Name == excluded[0] || fi.Name == excluded[1] ) continue;
try
{
fi.Delete();

subDir.Delete(true);
}
catch
{
//
}

if you add so after you will have 2 tests
one for directories and one for files


good luck

king_888
153

i tried to do that but there are 14 error!

Feedback