Reputation: 39
I have a small problem here. I want to list my files from a directory in a listbox. and when I double click the files I want to display the file in a textbox.
I got this code, but my directory when double click are wrong.
Say i double click on battalionAPC.fbi The directory diplay in textbox is C:\Users\Yvonne\Documents\Visual Studio 2010\Projects\ListBoxTest\ListBoxTest\bin[Debug\battalionAPC.fbi]
But the correct directory should be this: C:\Users\Yvonne\Documents\Visual Studio 2010\Projects\ListBoxTest\ListBoxTest\bin[units\battalion\APC\battalionAPC.fbi]
**Differences mark using the [] brackets
Any idea how I could get the directory correct?
My full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void populateList(string path)
{
string[] dir = Directory.GetDirectories(path);
foreach (string d in dir)
{
string entry = Path.GetFileName(d);
//listBox1.Items.Add(entry);
populateList(d);
}
string[] files = Directory.GetFiles(path);
foreach (string f in files)
{
string entry1 = Path.GetFullPath(f);
string entry = Path.GetFileName(f);
if (entry.Contains(".fbi"))
{
listBox1.Items.Add(entry);
}
}
}
private void Form1_Load_1(object sender, EventArgs e)
{
populateList(@"..\units\battalion");
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string file = listBox1.SelectedItem.ToString();
textBox1.Text = file;
string all = Path.GetFullPath(file);
textBox2.Text = all;
}
}
}
Upvotes: 0
Views: 7937
Reputation: 9075
private void populateList( string path )
{
string[] files = Directory.GetFiles(path, "*.fbi", SearchOption.AllDirectories);
foreach (string f in files)
{
string entry1 = Path.GetFullPath(f);
string entry = Path.GetFileName(f);
listBox1.Items.Add(entry);
}
}
You can use Directory.GetFiles() to do more work for you by using the variation with three parameters. The second parameter already limits the files found to those with the .fbi extension, and SearchOption.AllDirectories handles going down into subdirectories so you don't have to make populateList() recursive anymore.
Upvotes: 2
Reputation: 11818
keep a List in the background that matches the ListBox. Keep the value in "entry1" in that list.
When they double click on the item in the ListBox, you open the file from the List
Upvotes: 0
Reputation: 33242
You can use DirectoryInfo in order to enumerate the files and keeping all the info associated with a single files, since DirectoryInfo
returns an array of FileInfo
, storing the complete file name as well.
Upvotes: 0