2014-09-26 62 views
2

說我有這個輸入(base目錄)作爲字符串(當然也可以是不同的,更長的路徑):排除基本目錄(和文件名)的完整路徑

c:\Projects\ (could be also c:\Projects) 

與該輸入(在子目錄中的文件)的字符串:

c:\Projects\bin\file1.exe 
c:\Projects\src\folder\file2.exe 

是什麼讓這些字符串的最佳方式:

bin 
src\folder 

也就是說,從我想排除基本目錄(即給出)和文件名的完整路徑。

回答

3

您可以按照如下邏輯進行操作:

string root = @"c:\Projects"; 
string path = @"c:\Projects\src\folder\file2.exe"; 

path = path.Replace(root, "").Replace(Path.GetFileName(path), "").Trim('\\'); 

Console.WriteLine(path); 
  1. 替換該基地的目錄和文件名(帶擴展名),以空字符串。
  2. 修剪的bin\src\folder\
1

\字符可能結束,您可以使用

string s = @"c:\Projects\bin\file1.exe"; 
var split_s = s.Split(new char[]{'\\'}).Skip(2); 
Console.WriteLine(string.Join(@"\", split_s.Take(split_s.Count() - 1).ToArray())); 

Example IDEONE

這處分割斜線的字符串,跳過前兩個項目(該驅動器和項目文件夾),然後獲取下一個X數量的目錄 - 不包括文件名。然後將它連接在一起。

1

您可以使用下面的靜態方法來計算給定一個相對父路徑:

public static string GetRelativeParentPath(string basePath, string path) 
    { 
     return GetRelativePath(basePath, Path.GetDirectoryName(path)); 
    } 

    public static string GetRelativePath(string basePath, string path) 
    { 
     // normalize paths 
     basePath = Path.GetFullPath(basePath); 
     path = Path.GetFullPath(path); 

     // same path case 
     if (basePath == path) 
      return string.Empty; 

     // path is not contained in basePath case 
     if (!path.StartsWith(basePath)) 
      return string.Empty; 

     // extract relative path 
     if (basePath[basePath.Length - 1] != Path.DirectorySeparatorChar) 
     { 
      basePath += Path.DirectorySeparatorChar; 
     } 

     return path.Substring(basePath.Length); 
    } 

這是這樣,你可以使用它:

static void Main(string[] args) 
    { 
     string basePath = @"c:\Projects\"; 
     string file1 = @"c:\Projects\bin\file1.exe"; 
     string file2 = @"c:\Projects\src\folder\file2.exe"; 

     Console.WriteLine(GetRelativeParentPath(basePath, file1)); 
     Console.WriteLine(GetRelativeParentPath(basePath, file2)); 
    } 

輸出:

bin 
src\folder 
0

您還可以使用正則表達式,因爲它是字符串的問題,

string ResultString = null; 
try { 
    ResultString = Regex.Match(SubjectString, "c:\\\\Projects\\\\(?<data>.*?)\\\\(\\w|\\d)*  (\\.exe|.png|jpeg)", 
    RegexOptions.Multiline).Groups["data"].Value; 
} catch (ArgumentException ex) { 
// Syntax error in the regular expression 
} 

可以排除或包括多種文件類型,如我加爲png和jpeg.Drawback是字符串的開始部分必須由C啓動:/項目

相關問題