我正在努力extract the path from left to right based on the first match from left to right but only with the Folder name and not with the file name:

string numberToFind = "99999";

string filePath = "\\mydomain.com\TestEnv\MyApp\ImportantFiles\Phase 1\Employee\Folder 1\Folder 1.2\Folder 1.2.1_99999_PayRoll data\Folder 99999\JanSlip.pdf";

int resultIndex = data.LastIndexOf(numberToFind);
if(resultIndex!=-1)
{
   data = data.Substring(0,resultIndex);
}
Output - \\mydomain.com\TestEnv\MyApp\ImportantFiles\Phase 1\Employee\Folder 1\Folder 1.2\Folder 1.2.1_

Expected Output :

"\mydomain.com\TestEnv\MyApp\ImportantFiles\Phase 1\Employee\文件夹 1\Folder1.2\文件夹1.2.1_99999_Payroll Data

如你所见,我得到的输出与‘预期输出’不匹配.

请注意,我只想match the numberToFind on the folder level并根据第一个匹配项从左到右提取路径,但如果在文件夹级别上没有找到匹配项,我想返回整个路径.For eg:

string numberToFind = "99999";
    
string filePath = "\\mydomain.com\TestEnv\MyApp\ImportantFiles\Phase 1\Employee\Folder 1\Folder 1.2\99999_JunePayslips.pdf";

Expected output : \\mydomain.com\TestEnv\MyApp\ImportantFiles\Phase 1\Employee\Folder 1\Folder 1.2\99999_JunePayslips.pdf

推荐答案

Path.GetDirectoryName将得到不带最后一段的路径,并返回null作为根.Path.GetFileName会帮我们拿到最后一段.

因此,您可以使用以下迭代方法:

  • 获取给定路径的目录并将其存储在toSearch中.
  • While that is not null:
    • 判断最后一段是否包含您正在搜索的值.
    • 如果是,将当前的toSearch存储在found
    • 砍掉下一个目录段,然后循环.
  • 如果我们有的话还found,否则就给原来的path.

dotnetfiddle,注意小提琴使用了/个分隔符,因为它是在Linux/Unix上.

private static string FindPathByDirectory(string path, string toFind)
{
    var toSearch = Path.GetDirectoryName(path);
    string? found = null;
    while (toSearch != null)
    {
        if (Path.GetFileName(toSearch).Contains(toFind, StringComparison.OrdinalIgnoreCase))
            found = toSearch;
        toSearch = Path.GetDirectoryName(toSearch);
    }
    return found ?? path;
}

从右到左的方向走更简单,你可以在找到它后立即退出.

private static string FindPathByDirectory(string path, string toFind)
{
    var toSearch = Path.GetDirectoryName(path);
    while (toSearch != null)
    {
        if (Path.GetFileName(toSearch).Contains(toFind, StringComparison.OrdinalIgnoreCase))
            return toSearch;
        toSearch = Path.GetDirectoryName(toSearch);
    }
    return path;
}

Csharp相关问答推荐

ListaryImportProperty的默认DllImportSearchPathsProperty行为

EF Core判断是否应用了AsSplitQuery()

WPF Windows初始化正在锁定. Net 8中分离的线程

为什么总输出就像12.3没有一分一样?

如果属性名为xyz,我需要使用System.Text.Json修改字符串类型的值""<>

dotnet集合中内部数组的局部变量副本的用途是什么?'

如何在Windows 11任务调度程序中每1分钟重复一次任务?

Rider将.NET安装在哪里

StackExchange.Redis.RedisServerException:调用ITransaction.ExecuteAsync()时出现错误未知命令取消监视

为什么无法将对象转换为泛型类型

HelperText属性不支持复杂内容(混合C#和标记)

Blazor Fluent UI DialogService,<;FluentDialogProvider/>;错误

使用ASP.NET MVC for Lemon Squeezy X-Signature创建散列

C#无法将.csv列转换为用于JSON转换的列表

用MongoDB c#驱动程序删除和返回嵌套数组中的文档

如何在绑定到数据库的datagridview中向上或向下移动行

处理方法内部过滤与外部过滤

LINQ在GROUP BY和JOIN之后获取子列表

如何在C#中用Serilog记录类路径、方法名和行编号

从具有泛型类型约束的类继承-Blazor