最近项目中遇到一个问题,对两个目标路径进行操作。题设路径A和路径B
【要求】:遍历路径A中的所有文件,包括子目录的文件,然后提取数据后转移到路径B
【存在的问题】:路径A和路径B为用户配置项,如果用户将路径B配置为路径A的子目录。就会出现文件转移到B后,接下来遍历A会对B已提取的数据重复操作。
【解决方案】:对.NET类库还不够熟练,不知是否有直接的判断方法。自己设计了一个递归的方法也能实现判断功能,而且设计过程中也学习到不少东西,目前看来还是不错的。不过我还是希望有简便类库方法直接调用,请大牛们指点一二。
【设计思路】
A,B是路径用的FolderBrowserDialog选择的,所以不去判断其合法性和存在性。
对路径A进行遍历,获得其所有子目录的路径存入ArrayList中。循环ArrayList与B进行比对。
方案代码:
private bool ischild(string path_fa,string path_child) { if (path_fa == "" || path_child == "") { return false; } else { string exist = ""; ArrayList paths = new ArrayList(); this.for_path(@path_fa, ref paths);//递归方法 foreach (string @str in paths) { if (str.Equals(@path_child)) { exist = "子路径存在"; } } if (exist != "") { return true; } else { return false; } } }
循环递归方法代码:
/// <summary> /// 遍历递归路径的子目录 /// </summary> /// <param name="path">要遍历的路径</param> /// <param name="paths">子目录集合</param> private void for_path(string path,ref ArrayList paths) { string[] dirs = Directory.GetDirectories(path);//得到子目录 IEnumerator iter = dirs.GetEnumerator(); while (iter.MoveNext()) { string str = (string)(iter.Current); paths.Add(str); this.for_path(str,ref paths); } }
原文:http://www.cnblogs.com/Cheneyhu/p/3570977.html