【问题标题】:How do I search for a folder in a folder in c#?如何在 C# 中的文件夹中搜索文件夹?
【发布时间】:2026-01-26 08:30:02
【问题描述】:

我想检查特定文件夹是否存在于 c# 中的文件夹中。 目前我正在使用以下代码。

        string currentPath = Directory.GetCurrentDirectory();

        foreach (string subDir in Directory.GetDirectories(currentPath))
        {
            if (subDir == currentPath + @"\Database") // if "Database" folder exists
            {
                dbinRoot = true;
            }
        }
        if (dbinRoot == true)
        {
            currentPath = currentPath + @"\Database\SMAStaff.accdb";
        }
        else
        {
            for (int i = 0; i < 2; i++)
            {
                currentPath = currentPath.Remove(currentPath.LastIndexOf("\\"));
            }
            currentPath = currentPath + "\\Database\\SMAStaff.accdb";
        }

我想知道是否有更好的方法来做到这一点???

【问题讨论】:

    标签: c# directory datadirectory


    【解决方案1】:

    你可以使用:

    Directory.Exists(currentPath + @"\Database")
    

    【讨论】:

    • 我强烈建议使用 Path.Combine 而不是使用字符串连接来创建文件夹路径
    【解决方案2】:

    使用Path.Combine方法连接部分路径也更可靠

    if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"Database"))){}

    【讨论】:

      【解决方案3】:

      您可能正在直接寻找

      currentPath = Directory.GetCurrentDirectory();
      bool fileExists = File.Exists(Path.Combine(currentPath, "Database\\SMAStaff.accdb")))
      

      为了更好的可读性,for循环可能包含

      currentPath = Directory.GetParent(currentPath).FullName;
      

      【讨论】:

        最近更新 更多