1

I need to obtain in a new string the last element of a path. For ex, for the path

"C:\Users\MEDIACENTER\Desktop\Resurse_C#\Resurse\Imagini\Cluj1.txt"

I want to obtain "Cluj1.txt". Because I need a general method because I am working with a DataBase. The character '\' is the one that I have trouble with, because the C# syntax will not let me use it on the 3rd line of code:

01.    while (dr.Read()) // in dr[0] contains the jpg path
02.    {
02.           string v = dr[0].ToString();
03.           char c = '\'; 
04.           string[] s = v.Split(c);            
05.    }
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Alex Lazar
  • 103
  • 9
  • 1
    Is this what you're looking for? `string filename = Path.GetFilename(dr[0]);` – Lasse V. Karlsen Mar 02 '20 at 10:18
  • Note that `Path.GetFilename` can also be used to get the name of the last folder in a path that references a folder. Basically, `Path.GetFilename` does exactly what you're looking for, it is not limited to files, it will use the position of the last path separator and return everything after it. – Lasse V. Karlsen Mar 02 '20 at 10:19
  • 1
    the '\' character is the escape character - if you want to specify the backslash character you need to use '\\'. For more info see [How do I write the escape character to code](https://stackoverflow.com/questions/15748040/how-do-i-write-the-escape-char-to-code) – Ian Mar 02 '20 at 10:23
  • Thank you a lot for all of the information, the escape character made me a lot of problems and now I finally understood it! – Alex Lazar Mar 02 '20 at 10:30

1 Answers1

3

Have you tried Path.GetFileName

var filename = Path.GetFileName(@"C:\Users\MEDIACENTER\Desktop\Resurse_C#\Resurse\Imagini\Cluj1.txt");
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25