【问题标题】:C# Filter differences from a pathC#过滤路径中的差异
【发布时间】:2017-04-11 11:25:24
【问题描述】:

DirectoryPath = C:\Pics

filePath = C:\Pics\Dogs\dog.PNG

newPath 应该是:Dogs\dog.PNG


如何获得newPath? 我的代码 sn-p 不对


string directoryPath = "C:\\Pics";
string filePath = "C:\\Pics\\Dogs\\dog.PNG";

if (!directoryPath.EndsWith("\\"))
   directoryPath = directoryPath + "\\";

string newPath = filePath.Substring(filePath.LastIndexOf(directoryPath) + 1);

提前致谢!

【问题讨论】:

  • 看起来像XY problem 的情况。您确定要区分字符串而不是相对路径吗?
  • LastIndexOfIndexOf 返回子字符串开始的索引,而不是结束的索引。

标签: c# substring


【解决方案1】:

您能否在目录路径中附加一个反斜杠,然后在文件路径中将目录路径替换为空字符串

newPath = filePath.Replace(DirectoryPath + @"\", string.Empty);

如果 directoryPath 与 filePath 的开头不匹配,则 newPath 将保持不变。

在您编辑代码以显示反斜杠的条件添加之前,我确实发布了此内容 - 这样可以在上面的代码中删除。

【讨论】:

    【解决方案2】:

    您从LastIndexOf() 获得的int 索引将始终从最右边的值开始,在您的情况下为0。您还必须为此添加String.Lenght

    if (filePath.StartsWith(directoryPath))
    {
        string newPath =
           filePath.Substring(filePath.LastIndexOf(directoryPath) + directoryPath.Length + 1);
    }
    

    【讨论】:

    • 您应该检查原始文件路径的开头是否与目录路径匹配。
    • 使用此代码,您不能在 if 之外使用 newpath :)
    • @Pikoh 我不想让它太容易 OP ;)
    • @Smartis ok ok,很公平
    【解决方案3】:

    我会先检查filePath 是否包含DirectoryPath,所以我会这样做:

     var newPath=filePath.Contains(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
                                                 :filePath;
    

    或者更好,使用StartsWith

    var newPath=filePath.StartsWith(DirectoryPath)?filePath.Substring(DirectoryPath.Length + 1)
                                                 :filePath;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2021-07-09
      • 2017-10-10
      • 2022-07-14
      • 1970-01-01
      相关资源
      最近更新 更多