tags:

views:

47

answers:

3
+1  Q: 

Read file problem

Hello,

I can't find a solution for this problem:

I write a program, which reads all file in a directory and puts them in a listbox. When a user select a file from a listbox, the program reads the selected file and prints out some info...

The problem is that after the firs selection my program "stop working". He don't crash, but when I try to select another file he do nothing.

I figured out, that the problem is in:

private String porocilo(String s)
{
 file = "/path to file/";
 TextReader tr = new StreamReader(file); //<- problem here
 //...
 tr.close();
 return someinfo;
}
//..
//Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
 label1.Text = porocilo(listBox1.SelectedItems[0].ToString());
}

After removing that (problem) line the program normally select files, but without this I can't read files and my program don't do anything.

Can someone tell me where I'm wrong?

Br, Wolfy

A: 

It looks like you have a hard-coded path in your porocilo method. That is, new StreamReader is taking as it's argument, file, not s. So it will only ever open, one file, not the file you selected.

private String porocilo(String s)
{
 //file = "/path to/file" // not sure what this is...???
 TextReader tr = new StreamReader(s); //<- fix here
 //...
 tr.close();
 return someinfo;
}
C Johnson
If you have time you can add in code to verify that the file exists, and various other things too.
C Johnson
the file exist, because I get this list by reading it...
Wolfy
+2  A: 

If the code you posted is really the code you are using (plus the missing semicolon), then the reason you are not seeing anything happening is because your code keeps opening and reading the same file, not the file the user selected. You are setting file to a constant path/filename and read from that, and you are not making use of the s parameter.

Timwi
my mistake :) file = "/path to file/"+s
Wolfy
@Wolfy: Please use `Path.Combine` instead of slashes. :)
Timwi
A: 

In your List box Selected index change method you need to assign the selected value as shown below

 //Call function:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
 label1.Text = porocilo(listBox1.SelectedItem.Text);
}

Also check your "porocilo" function it uses the parameter corectly

skamale
porocilo parameters works fine, when I remove TextReader tr = new StreamReader(file); the filepath is changing...
Wolfy