Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining only the filename when using OpenFileDialog property "FileName"

I am trying to include only the filename of the file I've selected in the OpenFileDialog in the label1.Text property, but I haven't found a solution yet. I know I could use a method from the string class on the ofd instance to filter out the whole path to the file, but I would like to know if a smarter/quicker way exists?

OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Find song"; ofd.Filter = "MP3 files|*.mp3"; ofd.InitialDirectory = @"C:\"; if (ofd.ShowDialog() == DialogResult.OK) {    label1.Text = "" + ofd.FileName +""; } 
like image 485
Birdman Avatar asked Oct 17 '11 11:10

Birdman


People also ask

How do I get the selected file from OpenFileDialog box?

OpenFileDialog component opens the Windows dialog box for browsing and selecting files. To open and read the selected files, you can use the OpenFileDialog. OpenFile method, or create an instance of the System. IO.

What OpenFileDialog does in C#?

The OpenFileDialog component allows users to browse the folders of their computer or any computer on the network and select one or more files to open. The dialog box returns the path and name of the file the user selected in the dialog box.


2 Answers

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

like image 178
Waqas Raja Avatar answered Sep 28 '22 03:09

Waqas Raja


Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName); 
like image 34
Davide Piras Avatar answered Sep 28 '22 03:09

Davide Piras