是否有C#方法从参考路径获取文件夹的数量?
发布时间:2020-12-15 21:57:06 所属栏目:百科 来源:网络整理
导读:我正在寻找一个简单的API方法集,可以找出文件夹是否是另一个文件夹的子目录,以及它之间有多少步骤.就像是: int numberOfFoldersDown(string parentFolder,string subfolder) { ... } 它看起来很有用,虽然编写起来很乏味,所以我认为它应该在System.IO.Path或
我正在寻找一个简单的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:tempzz")); // 1 Console.WriteLine(NumberOfFoldersDown(@"c:temp2",@"c:tempzz")); // -1 Console.WriteLine(NumberOfFoldersDown(@"c:temp2",@"c:temp2zzhui55")); // 3 Console.WriteLine(NumberOfFoldersDown(@"c:temp2zz",@"c:temp2zzhui55")); // 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); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |