I have a list box and its populated by this method,
private void ToReadFromExcel_Load(object sender, EventArgs e)
{
string folderpath = @"\\gibson\users";
// Call the method to show available files
PopulateListBox(ExcelListBox, folderpath, "*.csv");
}
// To populate list box with csv files from given path
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}
String strItem;
foreach (Object selecteditem in ExcelListBox.SelectedItems)
{
strItem = selecteditem as String;
MessageBox.Show(strItem);
}
// read csv file information and insert into detail table
string filepath = @"\\gibson\users\CampManager.csv";
StreamReader sr = new StreamReader(filepath);
I hard coded the file path now, but I need to pass the filepath that was selected in the listbox. I have the file name in the variable stritem. If I want to pass the whole folder path how would I do that?
There is an ideal way. You should, instead of adding the
FileInfoobject’sName, should add theFileInfoobject itself. So later you will be able to retrieve any piece of info related to that object, in your case say size, parent folder etc, and not just file name. Do it like this:One thing you should take care of here is to set the
DisplayMemberproperty of the ListBox like this:What this does is to set the what property of the object in the listbox should be displayed. So here you choose
FileInfo.Namewhich is what you want. This is how typically custom objects are added to ListBoxes in WinForms. You do not add just the string part of it typically. Akin toDisplayMember, there is alsoValueMemberproperty which is used to assign a value for each object, probably some id or so, but in your case nothing.Few suggestions, 1) If you’re using .NET 4, then use
EnumerateFilesinstead ofGetFiles. The former is lazy and only yields a result when you start enumerating them (not beforehand), so it should be faster.2) Use a
usingclause to dispose your stream reader properly, since that wont lock your file. It’s always a good practice to make use ofusing. Its better on eyes than manual closing and disposing! Like this or so: