微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

是否有C#方法从参考路径获取文件夹的数量?

我正在寻找一个简单的API方法集,可以找出文件夹是否是另一个文件夹的子目录,以及它之间有多少步骤.就像是:

int numberOfFoldersDown(string parentFolder,string subfolder)  { ... }

它看起来很有用,虽然编写起来很乏味,所以我认为它应该在System.IO.Path或System.IO.Directory程序集中的某个地方,但我找不到任何有用的方法.这些功能是否可用,或者我应该自己编写?

解决方法

没有内置的AFAIK.

这是一个使用Path和Directory方法的递归示例:

internal class Program
{
    private static void Main(string[] args)
    {
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp\",@"c:\temp\"));                   // 0
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp\",@"c:\temp\zz\"));                // 1
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\",@"c:\temp\zz\"));               // -1
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\",@"c:\temp2\zz\hui\55\"));       // 3
        Console.WriteLine(NumberOfFoldersDown(@"c:\temp2\zz\",@"c:\temp2\zz\hui\55\"));    // 2

        Console.Read();
    }

    public static int NumberOfFoldersDown(string parentFolder,string subfolder)
    {
        int depth = 0;
        WalkTree(parentFolder,subfolder,ref depth);
        return depth;
    }

    public static void WalkTree(string parentFolder,string subfolder,ref int depth)
    {
        var parent = Directory.GetParent(subfolder);
        if (parent == null)
        {
            // Root directory and no match yet
            depth = -1;
        }
        else if (0 != string.Compare(Path.GetFullPath(parentFolder).TrimEnd('\\'),Path.GetFullPath(parent.FullName).TrimEnd('\\'),true))
        {
            // No match yet,continue recursion
            depth++;
            WalkTree(parentFolder,parent.FullName,ref depth);
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐