Question

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 ???

Was it helpful?

Solution

you can use:

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

OTHER TIPS

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

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

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top