【问题标题】:Exclude base directory (and also file name) from full path从完整路径中排除基目录(以及文件名)
【发布时间】:2014-11-21 03:02:21
【问题描述】:
假设我将此输入(基本目录)作为字符串(当然可以有不同的更长路径):
c:\Projects\ (could be also c:\Projects)
这个输入(子目录中的文件)作为字符串:
c:\Projects\bin\file1.exe
c:\Projects\src\folder\file2.exe
获取此类字符串的最佳方法是什么:
bin
src\folder
也就是说,我想从完整路径中排除基本目录(给定的)和文件名。
【问题讨论】:
标签:
c#
string
path
directory
【解决方案1】:
你可以遵循这样的逻辑;
string root = @"c:\Projects";
string path = @"c:\Projects\src\folder\file2.exe";
path = path.Replace(root, "").Replace(Path.GetFileName(path), "").Trim('\\');
Console.WriteLine(path);
- 将此基本目录和文件名(带扩展名)替换为空字符串。
- 修剪
\ 字符可能结尾的bin\ 或src\folder\
【解决方案2】:
你可以使用
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 个目录 - 不包括文件名。然后将其重新组合在一起。
【解决方案3】:
您可以使用以下静态方法来计算给定路径的相对父路径:
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
【解决方案4】:
你也可以使用正则表达式,因为它是字符串的问题,
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。缺点是字符串的初始部分必须从 C:/Project 开始