2012-02-25 68 views

回答

1

這應該做你想做的。

 string firstDirectory = "c:\\my\\dir"; 
     string secondDirectory = "c:\\my\\other\\file.ext"; 


     var first = firstDirectory.Split('\\'); 
     var second = secondDirectory.Split('\\'); 

     var directoriesToGoBack = first.Except(second); 
     var directoriesToGoForward = second.Except(first); 

     StringBuilder directory = new StringBuilder(); 

     bool initial = true; 
     foreach (string s in directoriesToGoBack) 
     { 
      if (initial) 
      { 
       initial = false; 
      } else 
      { 
       directory.Append('\\'); 
      } 
      directory.Append(".."); 

     } 

     foreach (string s in directoriesToGoForward) 
     { 
      directory.Append('\\'); 
      directory.Append(s); 
     } 
     Console.WriteLine(directory.ToString()); 
+0

謝謝 - 似乎將owrk,如果沒有兩個目錄在同一路徑具有相同的名稱。如果有人經過全面測試的解決方案,我將不勝感激。 – ChrisJJ 2012-02-26 22:02:54

相關問題