tags:

views:

94

answers:

4

Hi all, I want to delete all .rar extension file from all directory with particular drive. Say i have "D:\Test" under this i have created many .rar files or .zip files. Once the program run only all .rar file should be deleted and other extension files should remain same and it should display that how many no of rar files have been deleted. I can create n of files in n detpht of subdirectory but while program run all .rar files should be deleted. For this i have written a program, and i have created many files in that particular drive, but when i am running the application saying that there is no files i mean its always checking the else condition. Here is my code pls somebody modify it.

static void Main(string[] args)
{
    DirectoryInfo dirMain = new DirectoryInfo("D:\\Test");
    if (dirMain != null)
    {
        FileInfo[] dirRar = dirMain.GetFiles("*.rar", SearchOption.AllDirectories);
        if (dirRar != null && dirRar.Length > 0)
        {
            for (int i = 0; i < dirRar.Length; i++)
            {
                Console.WriteLine(dirRar[i].FullName);
                dirRar[i].Delete();
            }
            Console.WriteLine("Total no of files deleted" + dirRar.Length.ToString());
        }
        else
        {
            Console.WriteLine("There is no file");
        }
    }
    Console.ReadKey();
}
A: 

You code looks fine. If you are entering the else condition it means that there are either no .rar files under d:\test (or any subfolders) or that the account you are running your code under doesn't have read permissions to this folder.

Darin Dimitrov
A: 

Few suggestions:

  1. Check that the files or directory is not marked as hidden.
  2. Try FileInfo[] dirRar = dirMain.GetFiles("*.*"); Iterate on each file and check whether you are getting your rar file
Ramesh Soni
Thanks mr. Soni its working fine now...
A: 

It works here.

All rar-files in D:\Test was deleted.

Bård
+1  A: 

Works fine for me; maybe check that d:\Test exists? As an aside - note that the recursive overload of GetFiles is a bit flaky when it gets to complex permission sets. You would do better by doing the recursion manually, using try/catch around sub-folders:

int count = 0;
Queue<string> dirs = new Queue<string>();
dirs.Enqueue(@"d:\Test");
while(dirs.Count > 0) {
    string dir = dirs.Dequeue();
    try
    {
        foreach (string subdir in Directory.GetDirectories(dir))
        {
            dirs.Enqueue(subdir);
        }
    }
    catch (Exception ex) { Console.Error.WriteLine(ex); }// access denied etc

    foreach (string file in Directory.GetFiles(dir, "*.rar"))
    {
        try
        {
            File.Delete(file);
            count++;
        }
        catch (Exception ex) { Console.Error.WriteLine(ex); }// access denied etc
    }
}
Console.WriteLine("Deleted: " + count);
Marc Gravell