使用 DirectoryInfo[] 列出目录及其内容

发布于 2024-10-22 03:23:14 字数 4114 浏览 1 评论 0原文

这需要一些时间来解释,但请耐心等待。

我根据特定路径上子目录的存在情况,自动在数据库中创建项目和潜在客户记录。目录结构分为三层。我将顶层的代码指向将子目录(区域)返回到 DirectoryInfo 对象数组中,如下所示:

DirectoryInfo[] classARegions = dir.GetDirectories("*", SearchOption.TopDirectoryOnly);

我想要使用的目录是该区域级别的子目录,因此我使用以下方法迭代 DirectoryInfo 数组:

foreach (DirectoryInfo region in classARegions)

然后迭代Region DirectoryInfo 以相同的方式对象子目录:

DirectoryInfo[] prospects = region.GetDirectories("*", SearchOption.TopDirectoryOnly);

到目前为止一切正常。我遇到的问题是在处理完第一个区域的子目录并返回 ForEach 循环后,我发现我的前景数组没有重新初始化为空。相反,除了当前迭代的子目录之外,它现在还包括先前迭代的所有子目录。

我的问题归结为我是否做错了,或者是否有办法清空prospects数组,以便它只填充来自本次迭代区域的子目录?

* 整个方法发布在下面。

 public string UpdateProspectInfo()
    {
        int countAdded = 0;
        int countExisting = 0;
        int countAddedOverall = 0;
        int countExistingOverall = 0;

        StringBuilder summary = new StringBuilder();
        StringBuilder existing = new StringBuilder();
        StringBuilder added = new StringBuilder();
        string prospectDir = ConfigurationManager.AppSettings["ProspectDir"].ToString();

        // get list of folders in Class A
        DirectoryInfo dir = new DirectoryInfo(prospectDir);
        DirectoryInfo[] classARegions = dir.GetDirectories("*", SearchOption.TopDirectoryOnly);

        summary.Append("Found " + classARegions.Length + " Class A Regions.\r\n");

        foreach (DirectoryInfo region in classARegions)
        {
            string regionName = (region.Name.Length > 50 ? region.Name.Substring(0, 50) : region.Name);

            DirectoryInfo[] prospects = region.GetDirectories("*", SearchOption.TopDirectoryOnly);                
            summary.Append("\r\n  Region: " + regionName + " contains " + prospects.Length + " prospect folders.\r\n");                

            foreach (DirectoryInfo prospect in prospects)
            {                    
                string projNum;
                string projName;

                int seperator = prospect.Name.IndexOf("-");
                // go to next prospect if name doesn't contain a - character
                if (seperator == -1)
                    continue;

                projNum = prospect.Name.Substring(0, seperator);
                projName = prospect.Name.Substring(seperator + 1);

                ProjectCollection temp = new Select().From<Project>()
                .Where("ProjectName").IsEqualTo(projName)
                .ExecuteAsCollection<ProjectCollection>();

                if (temp.Count < 1)
                {
                    Project tempProj = new Project();
                    tempProj.ProjectNumber = projNum;
                    tempProj.ProjectName = projName;
                    tempProj.PMAssigned = "Joe Smith";
                    tempProj.PMUserID = 108;
                    tempProj.ProjectActivity = "Active";
                    tempProj.ProjectLead = "Lead";
                    //tempProj.Location = projNum.Substring(0,50);
                    tempProj.DirectoryPath = prospect.FullName;

                    tempProj.Save();
                    countAdded++;

                    added.Append("      " + projName + "\r\n");
                }
                else
                {
                    ((Project)temp[0]).DirectoryPath = prospect.FullName;
                    ((Project)temp[0]).Save();
                    countExisting++;
                }                    
            }

            // add summary for each region
            summary.Append("    Added " + countAdded + " prospects.\r\n");
            summary.Append(added.ToString());
            summary.Append("    Processed " + countExisting + " prospects that already existed in the database.\r\n");

            // update counts and continue to next region
            countAddedOverall += countAdded;
            countExistingOverall += countExisting;
            countAdded = 0;
            countExisting = 0;
        }           

        return summary.ToString();
    }

This is going to take a while to explain but bear with me.

I'm automating the creation of project and lead records in our database based on the existence of sub directories at a certain path. The directory structure is three levels deep. I point the code at the top level return the subdirectories (regions) into an array of DirectoryInfo objects like so:

DirectoryInfo[] classARegions = dir.GetDirectories("*", SearchOption.TopDirectoryOnly);

The directories I want to work with are subs of this region level so I iterate through the DirectoryInfo array with:

foreach (DirectoryInfo region in classARegions)

I then iterate through the region DirectoryInfo objects subdirectories in the same way:

DirectoryInfo[] prospects = region.GetDirectories("*", SearchOption.TopDirectoryOnly);

Everything is ok up to this point. The problem I run into is after I finish processing the first region's subdirectories and head back through the ForEach loop I find that my prospects array isn't re-initialized as empty. Instead it now includes all the sub directories from the prior iteration in addition to the subdirectories for the current iteration.

My question boils down whether I'm doing this wrong or if there a way to empty the prospects array so it's only populated with subdirectories from this iteration's region?

* Entire Method is posted below.

 public string UpdateProspectInfo()
    {
        int countAdded = 0;
        int countExisting = 0;
        int countAddedOverall = 0;
        int countExistingOverall = 0;

        StringBuilder summary = new StringBuilder();
        StringBuilder existing = new StringBuilder();
        StringBuilder added = new StringBuilder();
        string prospectDir = ConfigurationManager.AppSettings["ProspectDir"].ToString();

        // get list of folders in Class A
        DirectoryInfo dir = new DirectoryInfo(prospectDir);
        DirectoryInfo[] classARegions = dir.GetDirectories("*", SearchOption.TopDirectoryOnly);

        summary.Append("Found " + classARegions.Length + " Class A Regions.\r\n");

        foreach (DirectoryInfo region in classARegions)
        {
            string regionName = (region.Name.Length > 50 ? region.Name.Substring(0, 50) : region.Name);

            DirectoryInfo[] prospects = region.GetDirectories("*", SearchOption.TopDirectoryOnly);                
            summary.Append("\r\n  Region: " + regionName + " contains " + prospects.Length + " prospect folders.\r\n");                

            foreach (DirectoryInfo prospect in prospects)
            {                    
                string projNum;
                string projName;

                int seperator = prospect.Name.IndexOf("-");
                // go to next prospect if name doesn't contain a - character
                if (seperator == -1)
                    continue;

                projNum = prospect.Name.Substring(0, seperator);
                projName = prospect.Name.Substring(seperator + 1);

                ProjectCollection temp = new Select().From<Project>()
                .Where("ProjectName").IsEqualTo(projName)
                .ExecuteAsCollection<ProjectCollection>();

                if (temp.Count < 1)
                {
                    Project tempProj = new Project();
                    tempProj.ProjectNumber = projNum;
                    tempProj.ProjectName = projName;
                    tempProj.PMAssigned = "Joe Smith";
                    tempProj.PMUserID = 108;
                    tempProj.ProjectActivity = "Active";
                    tempProj.ProjectLead = "Lead";
                    //tempProj.Location = projNum.Substring(0,50);
                    tempProj.DirectoryPath = prospect.FullName;

                    tempProj.Save();
                    countAdded++;

                    added.Append("      " + projName + "\r\n");
                }
                else
                {
                    ((Project)temp[0]).DirectoryPath = prospect.FullName;
                    ((Project)temp[0]).Save();
                    countExisting++;
                }                    
            }

            // add summary for each region
            summary.Append("    Added " + countAdded + " prospects.\r\n");
            summary.Append(added.ToString());
            summary.Append("    Processed " + countExisting + " prospects that already existed in the database.\r\n");

            // update counts and continue to next region
            countAddedOverall += countAdded;
            countExistingOverall += countExisting;
            countAdded = 0;
            countExisting = 0;
        }           

        return summary.ToString();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荆棘i 2024-10-29 03:23:14

感谢@BrokenGlass 的评论,通过从另一个方向挖掘来解决这个问题。

解决方案:如果名称缺少“-”字符,我会跳过文件夹。在我的摘要电子邮件中,我没有考虑跳过的文件夹。返回的文件夹总数高于 countAdded 和 countExisting 的总和。再次浏览代码,我看到了这一行:

if (seperator == -1) continue;

每当我点击不带“-”字符的文件名时,我就会离开循环。

The solution to this was arrived at by digging in another direction thanks to the comment from @BrokenGlass.

Solution: I was skipping folders if the name lacked a "-" char. In my summary email I wasn't accounting for the skipped folders. The total # of folders came back higher than the sum of countAdded and countExisting. Walking through the code again led me to this line:

if (seperator == -1) continue;

I was leaving the loop anytime I hit a filename without a "-" character.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文