0

我有一个父文件夹,其中包含多个名为 Project-* 的文件夹(文件夹编号为 Project-1、Project-15、Project-253 等)。每个文件夹中都有一个 zip 文件,其名称始终为“project.zip”。这意味着当文件夹结构正确时,它应该始终是 TopFolder\Project-*\project.zip。

我正在尝试编写一个查看每个 Project-* 文件夹的程序,以查看 project.zip 文件是否嵌套在另一个文件夹中(例如:Project-*\newfolder\project.zip)

我有一些代码可以查找名为 Project-* 的文件夹,并在它们有子目录时列出它们,但它似乎将我的 project.zip 文件视为文件夹,因此它将所有内容显示为具有子目录。

 DirectoryInfo directory = new DirectoryInfo(txtbxOldFolder.Text);
            DirectoryInfo[] folders = directory.GetDirectories("*Project-*", SearchOption.AllDirectories);


            //finds folders nested in the folder
            var query = from folder in folders
                        where folder.GetFileSystemInfos().Length > 0 
                        select folder.FullName.ToString();
            foreach (string str in query)
            {
                //this adds the path of any Project-* folder with subdirectories
                listNestedFolder.Add(str);
            }

如前所述,上面的代码确实找到了任何带有子目录的 Project-* 文件夹,但它也找到了 Project-*\project.zip 中的任何文件夹。如何让它停止将 zip 文件识别为目录?

4

2 回答 2

3

GetFileSystemInfos()返回文件和文件夹。
你可能想打电话给GetDirectories().

为了获得更好的性能,您可以编写where folder.EnumerateDirectories().Any()

于 2012-08-13T17:14:33.077 回答
0

您可以尝试此逻辑来搜索嵌套文件或子目录结构中的任何其他差异:

        string topfolder = @"c:\temp\utils\";
        string filename = "project.zip";

        foreach (string dir in Directory.GetDirectories(topfolder, "Project-*", SearchOption.TopDirectoryOnly))
        {
            IEnumerable<string> files = Directory.GetFiles(dir, "*.*", SearchOption.TopDirectoryOnly).Select(f => Path.GetFileName(f));
            if (files.Count() > 1)
            #region if directory contains extra (unexpected) files
            {
                Console.WriteLine(string.Format("Directory {0} contains {1} files", dir, files.Count()));
            }
            #endregion if directory contains extra (unexpected) files

            if (!files.Contains(filename))
            {
                Console.WriteLine(string.Format("File is not found in {0}", dir));

                #region Searching for the file in depth

                files = Directory.GetFiles(dir, filename, SearchOption.AllDirectories);
                if (files.Count() > 0)
                {
                    Console.WriteLine("The file has been found too deep:");
                    foreach (string s in files)
                        Console.WriteLine(s);
                }

                #endregion Searching for the file in depth
            }

            #region Searching for extra (unexpected) subdirectories

            int dircount = Directory.GetDirectories(dir, "*.*", SearchOption.TopDirectoryOnly).Length;
            if (dircount > 0)
                Console.WriteLine(string.Format("Directory {0} contains {1} subdirectories", dir, dircount));

            #endregion Searching for extra (unexpected) subdirectories
        }

        Console.ReadLine();
于 2012-08-14T06:15:36.750 回答