【问题标题】:How can I use indexOf for string with "\"? [duplicate]如何将 indexOf 用于带有“\”的字符串? [复制]
【发布时间】:2020-03-13 14:30:09
【问题描述】:

我有一个带有文件路径的字符串,例如:C:\Users\Ekaterina\Desktop\3DTrajektorienplaner\Planungstool\Dromedary.stl

现在我只需要文件名:“Dromedary.stl”。

我试图找到 '\' 的最后一个索引,然后删除它之前的所有内容,但我收到一个错误,即 '\' 不能使用。

我也尝试过删除功能,但是这个路径总是有不同的长度,具体取决于计算机。

我该如何解决这个问题?

【问题讨论】:

  • 使用 Path.GetFileName 代替参见:docs.microsoft.com/en-us/dotnet/api/…
  • 但如果你确实需要反斜杠作为char,请使用`\`
  • '\' 是一个跳过字符,您需要跳过它,以便编译器理解它是一个字符: int index = yourPath.IndexOf(@"\");或 int index = yourPath.IndexOf("\\");

标签: c# string


【解决方案1】:

您可以使用 Getfilename 方法轻松获取文件名。 Read more on GetFileName

string fileName = @"C:\mydir\myfile.ext";
string result;

result = Path.GetFileName(fileName);

【讨论】:

    【解决方案2】:

    你必须转义那个字符:

    int index = yourPath.IndexOf("\\");
    

    不过,最好使用 Path 类

    【讨论】:

      猜你喜欢
      • 2013-05-21
      • 2014-03-23
      • 2011-04-09
      • 2021-12-02
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      相关资源
      最近更新 更多