繁体   English   中英

如何在C#的文件夹中搜索文件夹?

[英]How do I search for a folder in a folder in c#?

我想检查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";
        }

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

您可以使用:

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

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

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

您可能直接在寻找

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

并且for循环可能包含更好的可读性

currentPath = Directory.GetParent(currentPath).FullName;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM