有效的方法来决定文件或目录删除

时间:2013-06-26 14:04:34

标签: c# file-io io directory

我的方法获取字符串数组作为参数,表示我的程序必须删除的文件和目录的路径。在foreach循环中我不知道字符串是否代表文件或目录的路径,所以我不知道我应该使用哪种方法File.Delete()或Directory.Delete。

我创造了类似的东西,但我认为可以做得更好:)

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

有人知道如何更好地完成这些代码吗?

编辑:或者我认为它可能会更好

            if(File.Exists(path))
            {
                File.Delete(path);
                continue;
            }
            if(Directory.Exists(path))
            {
                Directory.Delete(path);
                continue;
            }

3 个答案:

答案 0 :(得分:1)

如果你想查看字符串是文件还是目录,只需检查它是否是两者之一;

foreach (string path in deleteItems)
{
  if(File.Exists(path)){
    File.Delete(path);
  }elseif(Directory.Exists(path)){
    Directory.Delete(path);
  }
}

答案 1 :(得分:1)

正如this answer中所述,您应该查看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);
}

(省略了异常处理以提高可读性)

答案 2 :(得分:0)

为什么不使用Directory.Exists(路径) 例如

if(Directory.Exists(path))

   Directory.Delete(path);

else

   File.Delete(path);