Obtaining only the filename when using OpenFileDialog property "FileName"

C#.NetFilenamesOpenfiledialog

C# Problem Overview


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 +"";
}

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBirdmanView Question on Stackoverflow
Solution 1 - C#Waqas RajaView Answer on Stackoverflow
Solution 2 - C#Davide PirasView Answer on Stackoverflow