gpt4 book ai didi

c# - 删除完整目录名称的一部分?

转载 作者:太空狗 更新时间:2023-10-29 23:10:48 25 4
gpt4 key购买 nike

我有一个完整路径的文件名列表,考虑到我有一个过滤器列表,我需要删除文件名和部分文件路径。

Path.GetDirectoryName(file)

完成部分工作,但我想知道是否有一种简单的方法可以使用 .Net 2.0 过滤路径以删除部分工作。

例如:

如果我的 path + filename 等于 C:\my documents\my folder\my other folder\filename.exe 而我所需要的就是上面的内容my folder\ 意味着我只需要从中提取my other folder

更新:

过滤器列表是一个文本框,文件夹名称由 , 分隔,所以我只是在上面有部分名称,就像上面的例子一样,这里的过滤器是 my folder

基于 Rob 代码的当前解决方案:

string relativeFolder = null;
string file = @"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');

foreach (string filter in filterArray)
{
int startAfter = Array.IndexOf(paths, filter) + 1;
if (startAfter > 0)
{
relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
break;
}
}

最佳答案

这样的事情怎么样:

private static string GetRightPartOfPath(string path, string startAfterPart)
{
// use the correct seperator for the environment
var pathParts = path.Split(Path.DirectorySeparatorChar);

// this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
// for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
int startAfter = Array.IndexOf(pathParts, startAfterPart);

if (startAfter == -1)
{
// path not found
return null;
}

// try and work out if last part was a directory - if not, drop the last part as we don't want the filename
var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
return string.Join(
Path.DirectorySeparatorChar.ToString(),
pathParts, startAfter,
pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
}

此方法尝试确定最后一部分是否为文件名,如果是则将其丢弃。

调用它
GetRightPartOfPath(@"C:\my documents\my folder\my other folder\filename.exe", "my folder");

返回

my folder\my other folder

调用它
GetRightPartOfPath(@"C:\my documents\my folder\my other folder\", "my folder");

返回相同。

关于c# - 删除完整目录名称的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5283236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com