blah blah blah is here! blah blah » Close

up1down
link

hello,

i need code to delete all files in my folder application except tow files

how can i do that?

For example:

my folder application "Debug"

file 1 = Debug.exe
file 2 = WindowsFormsApplication1.vshost.exe.manifest

last answered one year ago

1 answers

link

Try something like this:

using System.IO;

// ...

DirectoryInfo di = new DirectoryInfo("C:\\debug"); // or whatever it's called
FileInfo[] fia = di.GetFiles();
string[] excluded = { "Debug.exe", "WindowsFormsApplication1.vshost.exe.manifest" };
foreach (FileInfo fi in fia)
{
if (fi.Name == excluded[0] || fi.Name == excluded[1]) continue;
try
{
fi.Delete();
}
catch
{
MessageBox.Show(fi.Name + " could not be deleted");
}
}
fia = null;


EDIT

To delete subdirectories as well, including any files or subdirectories which they contain, then add this code to the above:
DirectoryInfo[] subDirs = di.GetDirectories();

foreach (DirectoryInfo subDir in subDirs)
{
try
{
subDir.Delete(true);
}
catch
{
MessageBox.Show(subDir.Name + " could not be deleted");
}
}
subDirs = null;

If you only want to get rid of subdirectories, provided they have no files in them, then change subDir.Delete(true) to subDir.Delete(false).

Notice that as the code stands it won't prevent deletion of excluded files which are in subdirectories rather than the parent directory. If you want to do this, I'll have to rewrite it to look at each subdirectory recursively.

king_888
153

thank you it work , but why i can't delete folder in debug?

vulpes
17279

FileInfo only deals with files. If you want to delete subdirectories as well, then please see my edit.

king_888
153

thank you

Feedback