string folder = @"D:\\General";
string[] files = Directory.GetFiles(folder, "*.txt");
foreach (string i in files)
listBox1.Items.Add(Path.GetFileNameWithoutExtension(i.Trim()));
In the above code i given a local drive as input to listbox and filtered the .txt files.
when i click a radio button the output will be displayed in a text box.
Then i made the items in listbox to appear only with name without extension.
When i make it, i face a exception in other codes below....
private void radiobtn_CheckedChanged(object sender, EventArgs e)
{
StreamReader objstream = new StreamReader(listBox1.Items[listBox1.SelectedIndex].ToString());-----here i face File Not Found exception
Textbox1.Text = objstream.ReadToEnd();
}
Can anyone help please??
Loading

Prakash TripathiRank #72 · 25.3K reputationPosted Apr 28, 2015, 10:35 PM EDT
I checked your problem by replicating your scenario in my local system. The problem with your code is that, you are not adding full file path into list box. Due to that when it tries to find the file, it fails.
Please note that, if you do not specify full path, it tries to find the path in below directory.
C:\Program Files (x86)\IIS Express\test1
and if it didn't find the file, it fails.
So to fix the problem, I can think of two kind solution as below.
1. Copy the files in IIS dorectory [Not Recommended] then you need to change code as below.
ListBox1.Items.Add(Path.GetFileName(i.Trim()));
2. Keep your files as is and change the code as below.
ListBox1.Items.Add(Path.GetFullPath(i.Trim()));
Hope this help.
Sabari Prabu10 reputationPosted Apr 29, 2015, 5:35 AM EDT
Prakash TripathiRank #72 · 25.3K reputationPosted May 1, 2015, 12:40 AM EDT
Attached the simple demo to explain what I mean, Please reply back for any clarification.
Manoj BhoirRank #599 · 4K reputationPosted May 1, 2015, 6:34 AM EDT
Change your radiobtn_CheckedChanged Code to :
StreamReader objstream = new StreamReader(folder + "\\" + listBox1.Items[listBox1.SelectedIndex].ToString() + ".txt");
textBox1.Text = objstream.ReadToEnd();
For more details please see attached sample code.