简体   繁体   中英

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!

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

如果cmdBrowse是一个OpenFileDialog ,那么,除非你期望列表框中有其他有意义的东西,否则你需要使用用户选择的路径(这是我怀疑你正在尝试做的事情),例如:

var fileName = Path.GetFileName(cmdBrowse.FileName);

查看在开始检索的路径上执行Path.GetFileNameWithoutExtension(FilePath)方法,然后将它们添加到框中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM