c# - 给定一个Path,如何判断它是目录还是文件

标签 c#

<分区>

我需要复制目录中的文件和目录。假设只有一层。

目录 C:\AAAA 包含 5 个其他目录(没有其他子目录的子目录)和 7 个文件。

当我打电话时:

System.IO.Directory.GetFileSystemEntries("C:\\AAAA");

返回一个字符串数组。它将包含按字典排序顺序排序的条目。所以当我调用 for-each 循环时:

foreach(string path in System.IO.Directory.GetFileSystemEntries("C:\\AAAA"))
{
    //how to determine path is dictonay or file??
}

那么从 System.IO.Directory.GetFileSystemEntries("C:\AAAA") 返回的数组中,如何确定给定路径是文件路径还是目录?

最佳答案

您可以使用 FileAttributes 发现字符串是表示文件还是目录。

   foreach(string currentName in Directory.GetFileSystemEntries("C:\\AAAA")) 
   { 
       FileAttributes att = File.GetAttributes(currentName);
       if((att & FileAttributes.Directory) == FileAttributes.Directory)
           // is a directory
       else
           // is a file
   }

与 File.Exist 或 Directory.Exist 相比,使用 FileAttributes 只有一个缺点。
如果文件或目录不存在,它会抛出异常,但根据您上面的代码,在这种情况下发生的可能性很小,并且 File.GetAttributes 比较快。

关于c# - 给定一个Path,如何判断它是目录还是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11136001/

相关文章:

c# - 表示为字符串的 2 个值的二进制加法

c# - 即使通过 SDK 成功登录 Facebook,BrowserSession.LoginComplete 事件也不起作用

c# - WCF WebService 中的 GZip 压缩

c# - Mac OSX 上的 Newtonsoft JSON.NET 6.0.8 和 Mono 以光荣的方式失败

c# - 从 C# 源文件中提取文档注释

c# - C# 中的 RSASSA-PSS

c# - 防止添加到公共(public)词典

c# - 编辑 WriteableBitmap 的原始像素数据?

c# - 剑锋GridEX : Cannot get the newly edited value on CellValueUpdated event

java - C#与Java之间的TCP通信编码问题