我有一个完整路径的文件名列表,我需要删除文件名和文件路径的一部分,考虑到我有一个过滤器列表.
Path.GetDirectoryName(file)
Run Code Online (Sandbox Code Playgroud)
部分工作,但我想知道是否有一种简单的方法来过滤路径使用.Net 2.0来删除它的一部分.
例如:
如果我有path + filename相同的C:\my documents\my folder\my other folder\filename.exe和所有我需要的是上面my folder\意味着我只需要从中提取my other folder.
更新:
过滤器列表是一个文件框,文件夹名称用a分隔,,所以我只有部分名称就像上面的例子一样,这里的过滤器就是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;
}
}
Run Code Online (Sandbox Code Playgroud)
这样的事情怎么样:
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));
}
Run Code Online (Sandbox Code Playgroud)
如果最后一部分是文件名,则此方法尝试计算,如果是,则删除它.
打电话给
GetRightPartOfPath(@"C:\my documents\my folder\my other folder\filename.exe", "my folder");
Run Code Online (Sandbox Code Playgroud)
回报
我的文件夹\我的其他文件夹
打电话给
GetRightPartOfPath(@"C:\my documents\my folder\my other folder\", "my folder");
Run Code Online (Sandbox Code Playgroud)
返回相同.
| 归档时间: |
|
| 查看次数: |
14577 次 |
| 最近记录: |