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

本文关键字:文件夹 文件 对象 何确定 | 更新日期: 2023-09-27 17:56:22

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

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

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

有没有办法做到这一点?

提前致谢

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

您可以使用 File.Exists 方法:

如果路径描述目录,则此 方法返回假

所以:

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);
} 

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。所以你必须抓住它(或使用达林·迪米特罗的方法)。

Try
    Dim isExistingFolder As Boolean = IsFolder(path)
    Dim isExistingFile = Not isExistingFolder 
Catch fnfEx As FileNotFoundException
    '.....
End Try 
var isDirectory = (File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;

System.IO.File.Exists("yourfilenamehere")就可以了。 如果路径不是文件的路径,这将返回 false。 如果路径不存在,它也会返回 false,所以要小心。

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

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.");
}
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] );

    }
}