删除部分完整目录名?
我有一个带有完整路径的文件名列表,考虑到我拥有的过滤器列表,我需要删除文件名和部分文件路径。
Path.GetDirectoryName(file)
完成部分工作,但我想知道是否有一种简单的方法可以使用 .Net 2.0 过滤路径以删除其中的一部分。
例如:
如果我的路径+文件名
等于C:\我的文档\我的文件夹\我的其他文件夹\文件名.exe
并且我所需要的就是上面的内容我的文件夹\
意味着我只需要从中提取我的其他文件夹
。
更新:
过滤器列表是一个文本框,其中文件夹名称由 ,
分隔,因此我只有部分名称,就像上面的示例一样,这里的过滤器将是 我的文件夹
基于 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;
}
}
I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.
Path.GetDirectoryName(file)
Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.
For example:
if I have the path + filename
equal toC:\my documents\my folder\my other folder\filename.exe
and all I need is what is above my folder\
means I need to extract only my other folder
from it.
UPDATE:
The filter list is a text box with folder names separated by a ,
so I just have partial names on it like the above example the filter here would be my folder
Current Solution based on Rob's code:
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的事情怎么样:
此方法尝试计算最后一部分是否是文件名,如果是,则将其删除。
调用它并
返回
调用它会
返回相同的结果。
How about something like this:
This method attempts to work out if the last part is a filename and drops it if it is.
Calling it with
returns
Calling it with
returns the same.
您可以使用此方法通过“\”符号(或 Unix 环境中的“/”)分隔路径。之后你会得到一个字符串数组,你可以选择你需要的。
you could use this method to split the path by "\" sign (or "/" in Unix environments). After this you get an array of strings back and you can pick what you need.