1

I want to extract the filename from a file path in C#.

For example:

textBox1.Text = "C:\Users\Elias\Desktop\image.png"

I want to copy the file name: "image.png" to the textBox2

How can i do that?

Legends
  • 21,202
  • 16
  • 97
  • 123

2 Answers2

4

Use the static Path.GetFileName method in System.IO:

Path.GetFileName(@"C:\Users\Elias\Desktop\image.png"); // --> image.png

regarding your example:

textBox2.Text = Path.GetFileName(textBox1.Text);
Legends
  • 21,202
  • 16
  • 97
  • 123
3

System.IO.FileInfo class can help with parsing that information:

textBox2.Text = new FileInfo(textBox1.Text).Name;

MSDN documentation on the FileInfo class: https://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.110).aspx

Mvarta
  • 518
  • 3
  • 7