How do I search for a folder in a folder in c#?
-
15-07-2021 - |
質問
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 ???
解決
you can use:
Directory.Exists(currentPath + @"\Database")
他のヒント
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;
所属していません StackOverflow