2014-09-26 63 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启动:/项目

相关问题