Search code examples
c#winformslistboxopenfiledialogfile-extension

Adding multiple filenames to listBox, but without extensions? C#


I'm making a program that adds executable files to a listBox in C#.

I'm trying to add the items to the listBox without the .exe extension. This is the code I had previously:

listBox1.Items.Add(openFiles.SafeFileNames.Replace(".exe",""));

It worked fine, but it doesn't have support for multiple files. When the code runs after selecting multiple items rather than one, it adds the item "System.String[]" (Which isn't good! D:)

Can I get some help? I'll try to explain this a little better, I haven't had much sleep so I might be rambling a bit -

I want to add multiple files to my listBox at the same time, with my openFileDialog that is set to multiSelect = true, but excluding the file extensions (.exe) from being entered into the listBox along with the individual items.

If this can't be done easily, I'll just switch back to single-select.


Solution

  • Use System.IO.Path.GetFileNameWithoutExtension(file) method.

    EDIT:

    foreach (string FileName in openFiles.SafeFileNames)
      {
        listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(FileName));
      }