2011-03-12 30 views
4

我有一個完整路徑的文件名列表,我需要刪除文件名和部分文件路徑考慮我有一個過濾器列表。刪除部分完整的目錄名稱?

Path.GetDirectoryName(file) 

做了部分工作,但我想知道是否有一種簡單的方法來過濾使用.Net 2.0刪除部分路徑的路徑。

例如:

,如果我有path + filename等於C:\my documents\my folder\my other folder\filename.exe和所有我需要的是什麼,是上述my folder\意味着我只需要my other folder從中提取。

UPDATE:

篩選器列表是由,分開的文件夾名稱的文本框,所以我只是有一個像上面的例子就可以了部分名稱這裏的過濾器將my folder

電流基於Rob代碼的解決方案:

string relativeFolder = null; 
string file = @"C:\foo\bar\magic\bar.txt"; 
string folder = Path.GetDirectoryName(file); 
string[] paths = folder.Split(Path.DirectorySeparatorChar); 
string[] filterArray = iFilter.Text.Split(','); 

foreach (string filter in filterArray) 
{ 
    int startAfter = Array.IndexOf(paths, filter) + 1; 
    if (startAfter > 0) 
    { 
     relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter); 
     break; 
    } 
} 
+0

你提到的過濾器是預編譯的目錄數組或其他? – 2011-03-12 15:03:40

+0

這是一個充滿文件夾名稱的文本框,用''隔開,忘了提及感謝評論。 – Prix 2011-03-12 15:14:58

回答

4

怎麼是這樣的:

private static string GetRightPartOfPath(string path, string startAfterPart) 
{ 
    // use the correct seperator for the environment 
    var pathParts = path.Split(Path.DirectorySeparatorChar); 

    // this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking 
    // for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead 
    int startAfter = Array.IndexOf(pathParts, startAfterPart); 

    if (startAfter == -1) 
    { 
     // path path not found 
     return null; 
    } 

    // try and work out if last part was a directory - if not, drop the last part as we don't want the filename 
    var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString()); 
    return string.Join(
     Path.DirectorySeparatorChar.ToString(), 
     pathParts, startAfter, 
     pathParts.Length - startAfter - (lastPartWasDirectory?0:1)); 
} 

此方法試圖制定出如果最後一部分是文件名並丟棄它,如果它是。

GetRightPartOfPath(@"C:\my documents\my folder\my other folder\filename.exe", "my folder"); 

回報

我的文件夾\我的其他文件夾

GetRightPartOfPath(@"C:\my documents\my folder\my other folder\", "my folder"); 

調用它調用返回相同的。

+0

非常感謝您的代碼,它幫助我以簡單和清晰的方式處理我的問題,我已經使用基於您的代碼的解決方案更新了我的主帖,並且正在爲我工​​作。 – Prix 2011-03-12 19:09:54

1

您可以使用此方法將路徑拆分爲「\」符號(或Unix環境中的「/」)。在此之後,你會得到一串字符串,你可以選擇你需要的。

 public static String[] SplitPath(string path) 
     { 
      String[] pathSeparators = new String[] 
      { 
       Path.DirectorySeparatorChar.ToString() 
      }; 
      return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries); 
     } 
+0

這就是我有的東西,文件夾被\\拆分\\我只是不知道如何從文件夾篩選器名稱中選擇所需的所有路徑,直到文件名開頭的結尾。 – Prix 2011-03-12 15:17:01

+2

小心你選擇目錄路徑分隔符。 「\」在Windows上是正確的,但可能不在其他平臺上。 – 2011-03-12 15:28:43

+3

@Prix:Rob的建議仍然是很好的建議。你可以使用'Path.DirectorySeparatorChar'而不是硬編碼。任何時候你都可以避免使用魔法字符串。 – Tergiver 2011-03-12 17:20:57