0

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
  • 19,109
  • 11
  • 87
  • 115

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
  • 19,109
  • 11
  • 87
  • 115
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
  • 498
  • 3
  • 7