更好的方式检查路径是文件还是目录?

490

我正在处理一个目录和文件的 TreeView。用户可以选择文件或目录,然后对其执行某些操作。这需要我编写一个方法,根据用户的选择执行不同的操作。

目前我正在做类似于下面的事情来确定路径是文件还是目录:

bool bIsFile = false;
bool bIsDirectory = false;

try
{
    string[] subfolders = Directory.GetDirectories(strFilePath);

    bIsDirectory = true;
    bIsFile = false;
}
catch(System.IO.IOException)
{
    bIsFolder = false;
    bIsFile = true;
}

我感觉一定有更好的方法!我希望能够找到标准的 .NET 方法来处理这个问题,但我没有找到。是否存在这样的方法?如果不存在,最直接的方法是确定一个路径是文件还是目录?


11
可以有人编辑问题标题,以明确指定“现有”的文件/目录吗?所有答案都适用于磁盘上存在的文件/目录的路径。 - Jake Berger
1
@jberger请参考我下面的答案。我找到了一种方法来处理可能存在或不存在的文件/文件夹路径。 - lhan
你是如何填充这个树形视图的?你是如何获取其中的路径的? - Random832
23个回答

0
只是添加一个特殊情况 - "文件夹选择" 在路径中。
在我的应用程序中,我会收到最近打开的路径传递给我,其中一些路径末尾带有"文件夹选择"。
一些FileOpenDialogs和WinMerge将"文件夹选择"添加到路径中(这是真实的)。

Dialog showing "Folder Selection." getting added to path

但在Windows操作系统下,“Folder Selection.”不是建议的文件或文件夹名称(永远不要这样做,愤怒地摇拳头)。 如此说道:http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx

不要以空格或句点结尾的文件或目录名称。虽然底层文件系统可能支持这些名称,但Windows shell和用户界面不支持。但是,将句点指定为名称的第一个字符是可以接受的。例如,“.temp”。

因此,虽然“Folder Selection.” 不应该被使用,但它是可以使用的。(太棒了)。

足够的解释-我的代码(我非常喜欢枚举):

public static class Utility
{
    public enum ePathType
    {
        ePathType_Unknown = 0,
        ePathType_ExistingFile = 1,
        ePathType_ExistingFolder = 2,
        ePathType_ExistingFolder_FolderSelectionAdded = 3,
    }

    public static ePathType GetPathType(string path)
    {
        if (File.Exists(path) == true) { return ePathType.ePathType_ExistingFile; }
        if (Directory.Exists(path) == true) { return ePathType.ePathType_ExistingFolder; }

        if (path.EndsWith("Folder Selection.") == true)
        {
            // Test the path again without "Folder Selection."
            path = path.Replace("\\Folder Selection.", "");
            if (Directory.Exists(path) == true)
            {
                // Could return ePathType_ExistingFolder, but prefer to let the caller known their path has text to remove...
                return ePathType.ePathType_ExistingFolder_FolderSelectionAdded;
            }
        }

        return ePathType.ePathType_Unknown;
    }
}

0

虽然我来晚了,但我发现Nullable<Boolean>返回值相当丑陋 - IsDirectory(string path)返回null并不等同于不存在的路径,除非有详细的注释说明,因此我想出了以下解决方案:

public static class PathHelper
{
    /// <summary>
    /// Determines whether the given path refers to an existing file or directory on disk.
    /// </summary>
    /// <param name="path">The path to test.</param>
    /// <param name="isDirectory">When this method returns, contains true if the path was found to be an existing directory, false in all other scenarios.</param>
    /// <returns>true if the path exists; otherwise, false.</returns>
    /// <exception cref="ArgumentNullException">If <paramref name="path"/> is null.</exception>
    /// <exception cref="ArgumentException">If <paramref name="path"/> equals <see cref="string.Empty"/></exception>
    public static bool PathExists(string path, out bool isDirectory)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (path == string.Empty) throw new ArgumentException("Value cannot be empty.", nameof(path));

        isDirectory = Directory.Exists(path);

        return isDirectory || File.Exists(path);
    }
}

这个辅助方法的编写旨在让人第一次阅读时就能理解其意图,同时又足够详细和简明。

/// <summary>
/// Example usage of <see cref="PathExists(string, out bool)"/>
/// </summary>
public static void Usage()
{
    const string path = @"C:\dev";

    if (!PathHelper.PathExists(path, out var isDirectory))
        return;

    if (isDirectory)
    {
        // Do something with your directory
    }
    else
    {
        // Do something with your file
    }
}

-6

这个行不行?

var isFile = Regex.IsMatch(path, @"\w{1,}\.\w{1,}$");

1
这不起作用,因为文件夹名称中可能会有句点。 - KSib
文件名称中不一定需要包含句点。 - Keith Pinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接