1

I'm currently creating a note taking application. I'm trying to add items to a listbox without their file extensions, I have tried GetAllFilesWithoutExtensions, but no luck. I'm currently able to add them but can't seem to remove the extension. Any advice would be greatly appreciated...

 DirectoryInfo dir = new DirectoryInfo("../Debug/");
 FileInfo[] files = dir.GetFiles("*.txt");

 foreach (FileInfo file in files)
 {
    listBox1.Items.Add(file);
 }
Alexey Zimarev
  • 17,944
  • 2
  • 55
  • 83
  • 2
    have you tried this? `Path.GetFileNameWithoutExtension(file.Name)` – Nikola.Lukovic Apr 15 '16 at 09:36
  • Hi @Nikola.Lukovic, Yes I have, unfortunately, it doesn't work. – JonnyAppleseed Apr 15 '16 at 09:40
  • can you show us what output you get when you run `Path.GetFileNameWithoutExtension(file.Name)` ? – Nikola.Lukovic Apr 15 '16 at 09:41
  • 1
    Ok, when "Path.GetFileNameWithoutExtension(file.Name)" is used, the program is unable to load the associated .txt files into a richTextBox... Which works with the extension... I suppose I'm just wanting to hide the extension. – JonnyAppleseed Apr 15 '16 at 09:48
  • This __use__ of the `ListBox` should have been in the original question; then you wouldn't have gotten all those answers that are rigth to the letter but missing the point ;-) – TaW Apr 15 '16 at 10:11

3 Answers3

7

You can use LINQ and System.IO.Path.GetFileNameWithoutExtension

var fileNamesWithoutExtension = files
    .Select(fi => System.IO.Path.GetFileNameWithoutExtension(fi.Name));
foreach(string fn in fileNamesWithoutExtension)
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

You could use System.IO.Path.GetFileNameWithoutExtension(string)

See MSDN

grmbl
  • 2,514
  • 4
  • 29
  • 54
0

Create a class to help you:

class FInfo
{
    public FileInfo Info { get; set; }

    public FInfo (FileInfo fi)    { Info = fi; }

    public override string ToString()
    {
        return Path.GetFileNameWithoutExtension(Info.FullName);
    }
}

Now fill the ListBox with instances of that class:

DirectoryInfo dir = new DirectoryInfo(yourPath);
FileInfo[] files = dir.GetFiles(yourFilter);

foreach (FileInfo file in files) listBox1.Items.Add(new FInfo(file));

Now you can access the full FileInfo data:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    FInfo fi = listBox1.SelectedItem as FInfo;
    if (fi != null) Console.WriteLine(fi.Info.FullName); // do your thing here!
}

And the ListBox will use the ToString method to display only the file names without path or extension..

TaW
  • 53,122
  • 8
  • 69
  • 111