我有这个路径:C:\Users\user\Documents\work\Template\workflow.xml
如何获取文件夹"模板"之后的部分?在"模板"文件夹之后,其他文件夹可以跟随。我不能使用 GetDirectoryName 方法。
谢谢。
你可以像这样使用string.Substring()
和string.IndexOf()
:
using System;
namespace Demo
{
public static class Program
{
static void Main()
{
string path = @"C:UsersuserDocumentsworkTemplateotherstuffworkflow.xml";
string target = @"Template";
int index = path.IndexOf(target, StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
path = path.Substring(index + target.Length);
Console.WriteLine(path);
}
else
{
// Error.
}
}
}
}
您可以使用它来获取模板和文件名之间的部分路径:
string path = @"C:UsersuserDocumentsworkTemplatefolder1folder2\workflow.xml";
string pathToExclude = @"DocumentsworkTemplate";
string pathExtracted = null;
if ( path.StartsWith(@"C:Users", StringComparison.OrdinalIgnoreCase) )
{
string directory = Path.GetDirectoryName(path);
int index = directory.IndexOf(pathToExclude, StringComparison.OrdinalIgnoreCase);
if ( index > 0 )
pathExtracted = Path.DirectorySeparatorChar
+ directory.Substring(index + pathToExclude.Length)
+ Path.DirectorySeparatorChar;
}
if ( pathExtracted == null )
Console.WriteLine("Bad path");
else
Console.WriteLine(pathExtracted);
结果
folder1folder2