/// <summary> /// 用于添加子节点 /// </summary> /// <param name="data"></param> /// <param name="depth"></param> private NTree(T data, NTree <T> parent, int depth) { this.data = data; this.parent = parent; this.depth = depth; children = new LinkedList <NTree <T> >(); }
public NTree(T data) { this.data = data; //默认是根节点 this.depth = 0; this.parent = null; children = new LinkedList <NTree <T> >(); }
/// <summary> /// 弹出一个子节点 并Remove /// </summary> /// <returns></returns> public NTree <T> PushChild() { if (children.Count > 0) { NTree <T> n = children.First.Value; children.RemoveFirst(); return(n); } return(null); }
/// <summary> /// 遍历路径 规则 一层一层的获取 先文件后子目录 /// /// 由于递归不便处理异常,特修改为循环遍历树形结构,以实现递归效果 xiecongwen 20140716 /// </summary> /// <param name="path"></param> /// <returns></returns> public IEnumerable Ls(SftpFile file) { var sshlog = new Common.Util.SSHLogManager(); NTree <SftpFile> parent = new NTree <SftpFile>(file); //后序遍历树 NTree <SftpFile> child = null; #region 自下而上 后序遍历 while (true) { string path = parent.Data.FullName; #region 判断是否有子节点 ps:将子目录添加到子节点,返回子文件 SftpFile[] dirs = null; SftpFile[] files = null; #region 获取 try { #region 获取子目录,并添加到子节点 dirs = TopDirLs(path); if (dirs != null && dirs.Count() > 0) { foreach (var dir in dirs) { parent.AddChild(dir); } } #endregion #region 获取子文件 files = TopFileLs(path); #endregion } catch (System.Exception ex) { parent.RemoveAllChildren(); //记录报错路径,并忽略其子目录 sshlog.WriteLog(new Common.Util.SSHLog() { DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Failure, Message = path }); logger.Error("FTPPath:" + path + Environment.NewLine + MessageUtil.GetExceptionMsg(ex, "")); //更新sftp连接对象 sftp = GetAvailableSFTP(); } #endregion //返回子文件 if (files != null && files.Count() > 0) { foreach (var f in files) { yield return(f); } } #endregion //判断是否有子节点 child = parent.PushChild(); if (child == null) { //如果没有子节点,则回溯至上层,否则跳出(表示遍历结束) again : if (parent.Depth > 0) { parent = parent.Parent; } else { yield break; } child = parent.PushChild(); if (child == null) { goto again; } } //作为父节点 进行循环 parent = child; } #endregion }