Beispiel #1
0
        public static IEnumerable <string> EnumFilesYield(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(path);
            }


            WIN32_FIND_DATA findData;

            NTree <string> parent = new NTree <string>(path);
            //后序遍历树
            NTree <string> child = null;

            while (true)
            {
                string tempPath   = parent.Data;
                string uncPath    = getUncPath(parent.Data);
                var    findHandle = FindFirstFile(uncPath, out findData);

                if (findHandle != INVALID_HANDLE_VALUE)
                {
                    try
                    {
                        do
                        {
                            if (findData.cFileName != "." && findData.cFileName != "..")
                            {
                                if (findData.dwFileAttributes == 16)
                                {
                                    parent.AddChild(tempPath + Path.DirectorySeparatorChar + findData.cFileName);
                                }
                                else
                                {
                                    yield return(tempPath + Path.DirectorySeparatorChar + findData.cFileName);
                                }
                            }
                        } while (FindNextFile(findHandle, out findData));
                    }
                    finally
                    {
                        FindClose(findHandle);
                    }
                }

                //判断是否有子节点
                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;
            }

            //log
            //Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
        }