Anonymous
Anonymous

Reputation: 13

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.

Upvotes: 1

Views: 3903

Answers (3)

KV Prajapati
KV Prajapati

Reputation: 94645

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

EDIT:

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

Upvotes: 4

RetroCoder
RetroCoder

Reputation: 2685

Use the FileInfo class. It has name with and without extensions, as well as with the entire directory name and filename as well. MSDN FileInfo

Upvotes: 0

Tim
Tim

Reputation: 28530

I think you'll need to do a loop, removing the ".exe" from each file name in the returned array:

foreach (string fileName in openFiles.SafeFileNames)
{
    listBox1.Items.Add(fileName.Replace(".exe",""));
}

Upvotes: 0

Related Questions