Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 决定删除文件还是删除目录的有效方法_C#_File Io_Io_Directory - Fatal编程技术网

C# 决定删除文件还是删除目录的有效方法

C# 决定删除文件还是删除目录的有效方法,c#,file-io,io,directory,C#,File Io,Io,Directory,我的方法获取字符串数组作为参数,它表示程序必须删除的文件和目录的路径。在foreach循环中,我不知道字符串是否表示文件或目录的路径,所以我不知道应该使用file.Delete()或directory.Delete哪个方法 我创造了这样的东西,但我认为可以做得更好:) 有人知道如何更好地编写这段代码吗 编辑:或者我认为会更好 if(File.Exists(path)) { File.Delete(path);

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

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

有人知道如何更好地编写这段代码吗

编辑:或者我认为会更好

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

如果您想查看字符串是否为文件或目录,只需检查它是否为两种类型之一

foreach (string path in deleteItems)
{
  if(File.Exists(path)){
    File.Delete(path);
  }elseif(Directory.Exists(path)){
    Directory.Delete(path);
  }
}
如中所述,您应检查:


(为了更好的可读性,省略了异常处理)

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


看看这个。是的,我觉得你最终会得出这样的结论:)
foreach (string path in deleteItems)
{
  if(File.Exists(path)){
    File.Delete(path);
  }elseif(Directory.Exists(path)){
    Directory.Delete(path);
  }
}
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);
}
if(Directory.Exists(path))

   Directory.Delete(path);

else

   File.Delete(path);