Md Nasimul Haq
Md Nasimul Haq

Reputation: 49

file deletion of specific folder

String userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
String dr = @"C:\Users\" + userName + @"\AppData\temp";

 DirectoryInfo dir = new DirectoryInfo(@dr);
 foreach (FileInfo file in dir.GetFiles())
 {
     file.Delete();
 }
 foreach (DirectoryInfo dire in dir.GetDirectories())
 {
     dire.Delete(true);
 }

i was using this for deleting contents of a folder and that should be depending upon the username of the computer & i have provided the admin privilege
but when any file doesnt delete it stops working at that file. i want this process to complete

Upvotes: 1

Views: 141

Answers (3)

Ofiris
Ofiris

Reputation: 6151

String userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
String dr = @"C:\Users\" + userName + @"\AppData\temp";
DirectoryInfo dir = new DirectoryInfo(@dr);
foreach (FileInfo file in dir.GetFiles())
{
    try
    {
        file.Delete();
    }
    catch (IOException ex)
    {//Log ex.message
        continue;
    }
}
foreach (DirectoryInfo dire in dir.GetDirectories())
{
    try
    {
        dire.Delete();
    }
    catch (IOException ex)
    { //Log ex.message
        continue;
    }
}

Moreover, I suggest you better use Path.Combine() instead of concatenating Strings.

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109852

If one of the files won't delete, the call to file.Delete() will throw an exception.

If you want to handle it, you must wrap it in a try/catch as follows:

foreach (FileInfo file in dir.GetFiles())
{
    try
    {
        file.Delete();
    }

    catch (IOException exception)
    {
        // Here you should log the exception.Message
    }
}

Upvotes: 1

gerrard00
gerrard00

Reputation: 1738

You'll have to add try/catch blocks around the file deletion statement, so that your loops continue even if you get an exception. I would recommend logging the list of files which have thrown exceptions when you call delete.

Upvotes: 1

Related Questions