2012-09-07 65 views
2

我可能沒有把標題說得太好,但希望我的解釋能說明問題。通過比較目錄路徑的一部分匹配子目錄

基本上,當給出另一個路徑進行比較時,我必須找出除文件名外的子目錄的名稱。例如,

Given: "C:\Windows\System32\catroot\sys.dll" 

Compare: "C:\Windows" 

Matched String: "\System32\catroot" 

再舉一例:

Given: "C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1" 

Compare: "C:\Windows\System32" 

Matched String: "\WindowsPowerShell\v1.0\Examples" 

什麼是執行此匹配的最佳方式?

回答

4

您可能還需要考慮特殊情況下,如:

  • 相對路徑

  • 短名稱如C:\PROGRA~1路徑爲C:\Program Files

  • 非經典路徑(C:\Windows\System32\..\..\file.dat

  • 路徑使用一個替代分離器(的/代替\

的一種方式是比較

例如之前轉換爲使用Path.GetFullPath規範完整路徑

string toMatch = @"C:\PROGRA~1/"; 
string path1 = @"C:/Program Files\Common Files\..\file.dat"; 
string path2 = @"C:\Program Files\Common Files\..\..\file.dat"; 

string toMatchFullPath = Path.GetFullPath(toMatch); 
string fullPath1 = Path.GetFullPath(path1); 
string fullPath2 = Path.GetFullPath(path2); 

// fullPath1 = C:\Program Files\file.dat 
// toMatchFullPath = C:\Program Files\ 
if (fullPath1.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase)) 
{ 
    // path1 matches after conversion to full path 
} 

// fullPath2 = C:\file.dat 
// toMatchFullPath = C:\Program Files\ 
if (fullPath2.StartsWith(toMatchFullPath, StringComparison.OrdinalIgnoreCase)) 
{ 
    // path2 does not match after conversion to full path 
} 
0

沒有必要使用正則表達式。
這可以很容易地使用string.StartsWith,string.SubstringPath.GetDirectoryName刪除文件名。

string fullPath = @"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"; 
string toMatch = @"C:\Windows\System32"; 
string result = string.Empty; 
if(fullPath.StartsWith(toMatch, StringComparison.CurrentCultureIgnoreCase) == true) 
{ 
    result = Path.GetDirectoryName(fullPath.Substring(toMatch.Length)); 
} 
Console.WriteLine(result); 

編輯:這變幻的從aiodintsov觀察護理,包括從@Joe約不規範或者部分路徑名的想法

string fullPath = @"C:\Windows\System32\WindowsPowerShell\v1.0\Examples\profile.ps1"; 
string toMatch = @"C:\Win"; 

string result = string.Empty; 
string temp = Path.GetDirectoryName(Path.GetFullPath(fullPath)); 
string[] p1 = temp.Split('\\'); 
string[] p2 = Path.GetFullPath(toMatch).Split('\\'); 
for(int x = 0; x < p1.Length; x++) 
{ 
    if(x >= p2.Length || p1[x] != p2[x]) 
      result = string.Concat(result, "\\", p1[x]); 
} 

在這種情況下,我認爲不完全匹配的應被認爲是不匹配的。 也看一看從@Joe的答案的部分或非標準的路徑問題

+0

這是否在最後刪除文件名?從外觀看,它看起來不像它。 – l46kok

+0

對不起,你錯過了這個問題的一部分。我更新了答案 – Steve

+0

另一個修改錯誤類型的小編輯。 – Steve