假设我有一个输入字符串(即基本目录),它是一个字符串(当然,路径长度可能不同):
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()));
这将在斜杠处分割字符串,跳过前两个条目(驱动器和项目文件夹),然后取下一个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
你也可以使用正则表达式,因为它与字符串有关。
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开始。