Delete everything in a directory except a file in C #

I am having trouble deleting everything in the directory except the file (index.dat) I am trying to clear the cookie folder and the temporary files folder, but I get an error when trying to delete index.dat because it is being used by another process. Is there a way to delete everything in the temp and cookies folder except the index.dat file? Here is my code:

string userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); string strDirLocalq = Path.Combine(userProfile, "AppData"); string strDirLocalw = Path.Combine(strDirLocalq, "Roaming"); string strDirLocale = Path.Combine(strDirLocalw, "Microsoft"); string strDirLocalr = Path.Combine(strDirLocale, "Windows"); string strDirLocalt = Path.Combine(strDirLocalr, "Cookies"); string[] filePaths = Directory.GetFiles(strDirLocalt); foreach (string filePath in filePaths) File.Delete(filePath); 
+6
c # file delete-file
source share
7 answers

It works:

 string[] filePaths = Directory.GetFiles(strDirLocalt); foreach (string filePath in filePaths) { var name = new FileInfo(filePath).Name; name = name.ToLower(); if (name != "index.dat") { File.Delete(filePath); } } 
+9
source share

Just place try / catch around File.Delete, because there may be more files being used that will also throw exceptions.

 try { File.Delete(filePath); } catch (Exception ignore) { } 
+3
source share

Check out this interesting solution!

 List<string> files = new List<string>(System.IO.Directory.GetFiles(strDirLocalt)); files.ForEach(x => { try { System.IO.File.Delete(x); } catch { } }); 

Feel the beauty of the tongue!

+3
source share
 string[] filePaths = Directory.GetFiles(strDirLocalt); foreach (string filePath in filePaths) try { File.Delete(filePath); } catch{ } } 
+1
source share

Just filter it from the list

 foreach (string filePath in filePaths.Where(!filePath.Contains("index.dat")) File.Delete(filePath); 
0
source share

Why not just catch the exception - there is a chance that any of the files might be used when trying to delete them.

 try{ // delete } catch{ } 
0
source share

One way that may still work is to boot into safe mode, and then assign yourself administrator rights, and then see if you can find the files to delete them.

Now I use the batch file creation method to rename the subfolder under the folder containing index.bat files, and then only copy the folders back to the original location that does not contain these files, but the resulting batch of files should be run from a separate Windows account that has full administrator rights.

0
source share

All Articles