Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete everything in a directory except a file in C#

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);
like image 750
llk Avatar asked Apr 01 '11 23:04

llk


People also ask

How do I delete all files except one file?

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.

How do I remove contents from a directory?

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.

How do you delete all files except the latest three in a folder windows?

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.


2 Answers

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);
    }
}
like image 173
Pol Avatar answered Oct 15 '22 03:10

Pol


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!

like image 37
Adi Avatar answered Oct 15 '22 04:10

Adi