I am having trouble deleting everything in a directory except a file (index.dat) I am trying to clear the cookies folder and the temp folder of files but I get an error when I try to delete index.dat because its 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);
Using rm command Here is the command to delete all files in your folder except the one with filename data. txt. Replace it with the filename of your choice. Here is the command to delete all files in your folder, except files data.
To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
xargs rm -r says to delete any file output from the tail . The -r means to recursively delete files, so if it encounters a directory, it will delete everything in that directory, then delete the directory itself.
This 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);
}
}
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 language!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With