如何检查路径是否包含至少一个文件夹C#

时间:2017-02-13 03:31:15

标签: c# file directory

示例:

File Paths:         | Output:
-----------------------------
C:\Abc\foo.txt      |  true
C:\Abc\foo\bar.txt  |  true
C:\nodir.txt        |  false
E:\nodir.txt        |  false
C:\Abc\             |  true
C:\Abc\def          |  true

如何查找给定路径是否在给定路径中包含至少一个文件夹(excluding the main drive folder like C:\)

目前我正在考虑是否可以按\进行拆分,看看它是否包含多个元素。对此有什么优雅的解决方案吗?

6 个答案:

答案 0 :(得分:2)

另一种选择:

private bool PathHasAtLeastOneFolder(string path)
{
    return Path.GetPathRoot(path).Length < Path.GetDirectoryName(path).Length;
}

答案 1 :(得分:1)

我希望这会对您有所帮助: - Directory.GetParent将为您提供给定路径的父文件夹的Directrory信息。如果其父级为null则表示它位于根目录中,否则它将是根目录下的子文件夹。

public bool myMethod(string currentPath)
{
    DirectoryInfo currentParent = Directory.GetParent(@"E:\nodir.txt");
    if (currentParent.Parent != null)
    {
        // if current parent is root means Parent will be null
        return true;
    }
    return false;
}

答案 2 :(得分:1)

根据我的评论,C:\nodir.txt之类的情况无法确定,因为它可能是文件或文件夹。

bool CheckIt(string path)
{
    IEnumerable<string> pathItems = path.Split(Path.DirectorySeparatorChar);

    var isFile = System.IO.File.Exists(path);
    if (isFile)
        pathItems = pathItems.Skip(1);

    if (Path.IsPathRooted(path))
        pathItems = pathItems.Skip(1);

    return pathItems.Any();
}

这将提供正确的答案,假设给定的路径实际存在于系统

如果您希望无论是否存在文件,您必须假设以扩展名结尾的路径是文件,而不是文件夹。在这种情况下,您可以使用以下方法更新方法:

var isFile = Path.GetFileNameWithoutExtension(path) != Path.GetFileName(path);

答案 3 :(得分:0)

这可能会为你做到这一点

if((test.Split('\\').Length - 1)>=2)
{
    //You have more than one folder
}
else
{
    //One file no folder
}

另一个想法可能是

class Program
{
    static void Main()
    {
        if(TextTool.CountStringOccurrences(Filetest, "\\")>=2)
        {
            //You have more than one folder
        }
        else
        {
            //One file no folder
        }
    }
}

public static class TextTool
{
    public static int CountStringOccurrences(string text, string pattern)
    {
        // Loop through all instances of the string 'text'.
        int count = 0;
        int i = 0;
        while ((i = text.IndexOf(pattern, i)) != -1)
        {
            i += pattern.Length;
            count++;
        }
        return count;
    }
}

答案 4 :(得分:0)

使用LINQ来计算反斜杠(\)字符的出现可能最容易实现,并且会产生比Split更好的性能:

var isRoot = myString.Count(c => c == '\\') > 1;

答案 5 :(得分:0)

您可以检查路径的父级是否是根驱动器:

public bool DoesPathContainFolders(string path)
{
    // Double check in case the given path *is* a root drive.
    string parent = Path.GetDirectoryName(path);
    return parent != null && parent != Path.GetPathRoot(path);
}

或另一种方法:

public bool DoesPathContainFolders(string path)
{
    // Double check in case the given path *is* a root drive.
    string parent = Path.GetDirectoryName(path);
    return parent != null && Path.GetDirectoryName(parent) != null;
}