如何确定对象是文件还是文件夹

时间:2011-05-14 21:17:11

标签: c# file file-io filepath

我正在尝试确定给定路径是指向文件还是目录。目前我的逻辑很简单,涉及以下检查

if (sourcePath.Contains(".")) // then treat this path as a file 

上面的问题是文件夹名称也可以包含句点。我希望能够确定给定的路径是文件的路径,而不必尝试实例化文件流类型并尝试访问它或类似的东西。

有没有办法做到这一点?

提前致谢

6 个答案:

答案 0 :(得分:10)

您可以使用File.Exists方法:

  

如果path描述了一个目录,那么这个   方法返回false

所以:

if (File.Exists(sourcePath))
{
    // then treat this path as a file
}

还有Directory.Exists方法,文档中给出了以下示例:

if(File.Exists(path)) 
{
    // This path is a file
    ProcessFile(path); 
}               
else if(Directory.Exists(path)) 
{
    // This path is a directory
    ProcessDirectory(path);
}
else 
{
    Console.WriteLine("{0} is not a valid file or directory.", path);
} 

答案 1 :(得分:3)

C#:

public bool IsFolder(string path)
{
    return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}

VB.Net:

Public Function IsFolder(path As String) As Boolean
    Return ((File.GetAttributes(path) And FileAttributes.Directory) = FileAttributes.Directory)
End Function

如果文件不存在,此函数将抛出File not found exception。所以你必须抓住它(或使用Darin Dimitrow的方法)。

Try
    Dim isExistingFolder As Boolean = IsFolder(path)
    Dim isExistingFile = Not isExistingFolder 
Catch fnfEx As FileNotFoundException
    '.....
End Try 

答案 2 :(得分:1)

var isDirectory = (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;

答案 3 :(得分:0)

System.IO.File.Exists("yourfilenamehere")会做到这一点。如果路径不是文件,则返回false。如果路径不存在,它也会返回false,所以要小心。

答案 4 :(得分:0)

通过谷歌搜索,我发现了这个:

public bool IsFolder(string path)
{
    return ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory);
}

然后您可以按如下方式调用该函数:

// Define a test path
string filePath = @"C:\Test Folder\";

if (IsFolder(filePath)){
    MessageBox.Show("The given path is a folder.");
}
else {
    MessageBox.Show("The given path is a file.");
}

答案 5 :(得分:0)

List<string> RtnList = new List<string>();
foreach (string Line in ListDetails)
{
    if (line.StartsWith("d") && !line.EndsWith("."))
    {
        RtnList.Add(line.Split(' ')[line.Split(' ').Length - 1] );


    }
}