0

I have a string with path for file like this for example: C:\Users\Ekaterina\Desktop\3DTrajektorienplaner\Planungstool\Dromedary.stl

Now I need only the name of the file: "Dromedary.stl".

I have tried to find the last index of '\' and then delete everything before it, but I get an error, that '\' cannot be used.

I have also tried with remove function, but this path always has different length depending on the computer.

How can I solve this problem?

Tsahi Asher
  • 1,767
  • 15
  • 28
Katja
  • 11
  • 1
  • 6
    Use Path.GetFileName instead See: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netframework-4.8 – Steve Nov 18 '19 at 08:54
  • 2
    But if you ever *do* need backslash as a `char`, use `\\` – Jon Skeet Nov 18 '19 at 08:55
  • '\' is a skipping char, you need to skip it so the compiler understand thats its a char instead : int index = yourPath.IndexOf(@"\"); or int index = yourPath.IndexOf("\\"); – Erwin Draconis Nov 18 '19 at 09:08

2 Answers2

4

You can use Getfilename method to get the filename easily. Read more on GetFileName

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

result = Path.GetFileName(fileName);
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
2

You have to escape that character:

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

However, the best would be to use Path class

CR0N0S.LXIII
  • 349
  • 2
  • 11