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

76 Views Asked by At

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!

2

There are 2 best solutions below

0
On BEST ANSWER

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);
0
On

How to remove .mp3 / .mpeg extensions from multiple selected files

You can use Path.GetFileNameWithoutExtension method to get the file name without extension:

var fileName = Path.GetFileNameWithoutExtension("path");

b) When the multiple files are added to the listbox. How can I set a max character length (50 chars)

Use Substring

fileName = fileName.Substring(0, 50);