从完整路径中排除基本目录(以及文件名)
本文关键字:文件名 路径 排除 | 更新日期: 2023-09-27 18:24:41
假设我有这个输入(基本目录)作为字符串(当然可以有不同的更长路径):
c:'Projects' (could be also c:'Projects)
并且该输入(子目录中的文件)为字符串:
c:'Projects'bin'file1.exe
c:'Projects'src'folder'file2.exe
获得此类字符串的最佳方法是什么:
bin
src'folder
也就是说,我想从完整路径中排除基本目录(给定的)和文件名。
您可以遵循以下逻辑:;
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'
的可能末尾的'
字符
您可以使用
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()));
IDEONE 示例
这会在斜杠处拆分字符串,跳过前两个条目(驱动器和项目文件夹),然后获取下一个X个目录(不包括文件名)。然后将其重新连接在一起。
您可以使用以下静态方法来计算给定路径的相对父路径:
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
您也可以使用Regex,因为它是字符串、的问题
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 开始