I have a listbox and it has some files loaded from a directory folder.
Code to load the files into the listBox1:
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listbox1, @"C:\TestLoadFiles", "*.rtld");
}
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);
}
}
I want to read and display the attributes values to the labels in the form. The loaded files in the listBox1, here is the code:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string path = (string)listBox1.SelectedItem;
DisplayFile(path);
}
private void DisplayFile(string path)
{
string xmldoc = File.ReadAllText(path);
using (XmlReader reader = XmlReader.Create(xmldoc))
{
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "description":
if (!string.IsNullOrEmpty(reader.Value))
label5.Text = reader.Value; // your label name
break;
case "sourceId":
if (!string.IsNullOrEmpty(reader.Value))
label6.Text = reader.Value; // your label name
break;
// ... continue for each label
}
}
}
}
Problem:When I click on the file in the listBox1 after the form is loaded,the files are loaded from the folder into the listbox but it’s throwing an error File not found in the directory.
How can I fix this problem???
That is because you are adding
File.Nameinstead you should addFile.FullNamein your listboxso your method PopulateListBox should become:
EDIT:
It looks like you want to display only the file name, not the full path. You could follow a following approach. In PopulateListBox, add
fileinstead of file.FullName so the line should beThen in SelectedIndexChanged event do the following:
This should get you the full name (file name with path) and will resolve your exception of File Not Found