Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting file name from the file path in C#?

I've seen a couple similar questions but I can't figure out what I'm doing wrong. I have a list box where I want all selected test files to be listed without the whole path. With this current code, no text is being entered into the list box. Where am I going wrong?

if (cmdBrowse.ShowDialog() == DialogResult.OK)
{
    string testNameShort = Path.GetFileName(listboxTestsToRun.Text.ToString());
    listboxTestsToRun.Items.Add(testNameShort);
}

Thanks in advance!

like image 624
Joel Avatar asked Dec 28 '25 03:12

Joel


1 Answers

Supposing that cmdBrowse is an OpenFileDialog and you want the filename selected by your user to be added to the listbox. In this case you code this

if (cmdBrowse.ShowDialog() == DialogResult.OK)
{
   if(cmdBrowse.FileName.Length > 0)
   {
      string testNameShort = Path.GetFileName(cmdBrowse.FileName);
      listboxTestsToRun.Items.Add(testNameShort);
   }
}
like image 162
Steve Avatar answered Dec 30 '25 17:12

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!