How do I search for a folder in a folder in c#?

124 views Asked by At

I want to check if a specific folder exists in a folder in c#. Currently I'm using the following code.

        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";
        }

I wish to know if there is a better way of doing this ???

3

There are 3 answers

1
andy On BEST ANSWER

you can use:

Directory.Exists(currentPath + @"\Database")
0
Alexander Eroma On

It also more reliably to use Path.Combine method to concatenate parts of path

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

0
rudolf_franek On

You are probably directly looking for

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

And the for cycle may contain for better readability

currentPath = Directory.GetParent(currentPath).FullName;