3

I'm calling a list of strings from a server.

At the moment I'm getting the full name and file extension like:

Image1.jpg

image2.png

test_folder.folder

I have some code that relies on the knowing what the extension is, however I also need to access the name of the item I've selected with out the extension.

So far my two attempts have been the following:

_clickedFolder = listBox1.SelectedItem.ToString() - "folder";
_clickedFolder.Trim(new Char[] { '.folder' });

but neither of these work.

What is the correct way to take the file extension away and just have the file name display?

Community
  • 1
  • 1
Sean
  • 897
  • 4
  • 20
  • 42

3 Answers3

17

Use the Path class:

string fnWithoutExtension = Path.GetFileNameWithoutExtension(path);

or

string extension = Path.GetExtension(path);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

You can try this:

string name = "set this to file name";
name = name.Substring(0,name.LastIndexOf('.'));
ismellike
  • 629
  • 1
  • 5
  • 14
0

Try this;

    private void listBox1_SelectionIndexChanged(object sender,EventArgs e)
    {
    string item = listBox1.SelectedItem.ToString();
    int index = item.LastIndexOf('.');
    if (index >= 0)//It's a valid file
    {
        string filename = item.Substring(0, index );
        MessageBox.Show(filename);
    }
    else if (index == -1)//Not a valid file
    {
        MessageBox.Show("The selected file is invalid.");
    }
    }
devavx
  • 1,035
  • 9
  • 22