2012-10-29 84 views
0

我想檢查一個特定的文件夾是否存在於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"; 
     } 

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

回答

4

你可以使用:

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

非常感謝兄弟 –

+0

我強烈建議您使用Path.Combine,而不是使用字符串連接創建文件夾路徑 – Charleh

0

它也更可靠地使用Path.Combine方法來連接路徑

的部分

如果(Directory.Exists(Path.Combine(Directory.GetCurrentDirectory() @ 「數據庫」))){}

0

你可能會直接找

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

而對於週期可能包含可讀性更好

currentPath = Directory.GetParent(currentPath).FullName;