ilyas elouazzani
ilyas elouazzani

Reputation: 31

How to get file name from a path in c#

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?

Upvotes: 2

Views: 1907

Answers (2)

Legends
Legends

Reputation: 22672

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);

Upvotes: 5

Mvarta
Mvarta

Reputation: 548

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

Upvotes: 3

Related Questions