2015-07-21 138 views
-2

我试图检查路径删除目录或文件路径的目录或文件。我发现此代码:检查路径是目录或文件的C#

FileAttributes attr = File.GetAttributes(@"C:\Example"); 
if (attr.HasFlag(FileAttributes.Directory)) 
    MessageBox.Show("It's a directory"); 
else 
    MessageBox.Show("It's a file"); 

但是,此代码不适用于已删除的目录或文件。

我有两个文件夹

C:\Dir1 
C:\Dir2 

Dir1中有正常的文件,如“的test.txt”,在Dir2中也有像“test.rar”或“test.zip”的压缩文件,我需要删除Dir1中的文件时删除Dir2中的文件。

东西我试过了,但没有任何工程。

有没有可能做到这一点?

谢谢!

+7

如果它已被删除,不再存在,它的问题是什么时,它的存在? –

+0

不过,我需要从另一个文件夹中删除这一点,所以我需要知道,如果它的文件或 –

+0

(因为扩展的)目录中你需要将其删除(这将在未来发生),或者你想检查删除了哪些内容文件或目录是否存在(发生在过去)? –

回答

1

如果路径所代表的对象不存在或已被从文件系统中删除,你要做的是代表一个文件系统路径的字符串:它不是什么。

用于指示路径旨在是一个目录(而不是一个文件)的正常惯例是与目录分隔符来终止它,所以

c:\foo\bar\baz\bat 

被取为表示一个文件,而

c:\foo\bar\baz\bat\ 

被用来表明目录。

如果你想要的是删除文件系统条目(可以是文件或目录,递归删除其内容和子目录),像应该足够了:

public void DeleteFileOrDirectory(string path) 
{ 

    try 
    { 
    File.Delete(path) ; 
    } 
    catch (UnauthorizedAccessException) 
    { 
    // If we get here, 
    // - the caller lacks the required permissions, or 
    // - the file has its read-only attribute set, or 
    // - the file is a directory. 
    // 
    // Either way: intentionally swallow the exception and continue. 
    } 

    try 
    { 
    Directory.Delete(path , true) ; 
    } 
    catch (DirectoryNotFoundException) 
    { 
    // If we get here, 
    // - path does not exist or could not be found 
    // - path refers to a file instead of a directory 
    // - the path is invalid (e.g., on an unmapped drive or the like) 
    // 
    // Either way: intentationally swallow the exception and continue 
    } 

    return ; 
} 

应该注意的是有在此过程中可能抛出的任何数量的异常。

相关问题