Search code examples
c#stringopenfiledialog

Removing extension from multiple selected files and only using 50 characters of it


I have two separate questions:

a) How to remove .mp3 / .mpeg extensions from multiple selected files
b) When the multiple files are added to the listbox. How can I set a max character length (50 chars)

String[] files, paths;
private void addbutton_Click(object sender, EventArgs e)
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        files = openFileDialog1.SafeFileNames;
        paths = openFileDialog1.FileNames;
        for (int x = 0; x < files.Length; x++)
        {
            listBox1.Items.Add(files[x]);
            // How can I remove the file extentions here? I know I can't use substring right?
            // Only use 50 chars after chopping off the extentions
        }
    }
}

I searched google but there are no answers relating to multiple files. Thanks guys!


Solution

  • You can use Path.GetFileNameWithoutExtension and String.Remove:

    string fileWithOutExtension = System.IO.Path.GetFileNameWithoutExtension(files[x]);
    if (fileWithOutExtension.Length > 50)
        fileWithOutExtension = fileWithOutExtension.Remove(50);
    listBox1.Items.Add(fileWithOutExtension);