-1

My method get array of string as an argument, that represent paths to files and directories that my program have to delete. In foreach loop i have no idea if string represent path to file or directory, so i don't know which method i should use File.Delete() or Directory.Delete.

I create something like this but i think it could be done better :)

foreach (string path in deleteItems)
        {
            try
            {
                Directory.Delete(path, true);
            }   
            catch (IOException)
            {
                try { File.Delete(path); }
                catch (IOException e) { Console.WriteLine(e); }
            }
        }

Somebody have any idea how to do this code better?

Edit: or i think it could be better

            if(File.Exists(path))
            {
                File.Delete(path);
                continue;
            }
            if(Directory.Exists(path))
            {
                Directory.Delete(path);
                continue;
            }
Mariyan
  • 664
  • 6
  • 20
Zabaa
  • 327
  • 1
  • 4
  • 16
  • 4
    Check this [previous question](http://stackoverflow.com/questions/1395205/better-way-to-check-if-path-is-a-file-or-a-directory-c-net). – Sander Jun 26 '13 at 14:07

3 Answers3

1

If you want to see whether or not the string is a file or a directory, simple check to see whether it is one of the two using;

foreach (string path in deleteItems)
{
  if(File.Exists(path)){
    File.Delete(path);
  }elseif(Directory.Exists(path)){
    Directory.Delete(path);
  }
}
Sander
  • 1,264
  • 1
  • 16
  • 26
1

As mentioned in this answer you should check the FileAttributes:

foreach (string path in deleteItems)
{
    FileAttributes attr = File.GetAttributes(@"c:\Temp");
    //detect whether its a directory or file
    if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
        Directory.Delete(path, true);
    else
        File.Delete(path);
}

(omitted exception handling for better readability)

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Why not use Directory.Exists(path) for eg

if(Directory.Exists(path))

   Directory.Delete(path);

else

   File.Delete(path);
Mariyan
  • 664
  • 6
  • 20
AAB
  • 1,594
  • 2
  • 25
  • 40