-5

I'm using C# to open a text file then I read everything inside it with this code:

OpenFileDialog pic = new OpenFileDialog();
pic.ShowDialog();

System.IO.StreamReader file = new System.IO.StreamReader(pic.OpenFile());
a=file.readline();

After I've finished reading, I want to read the data again but it tells me it's empty - how can I read it again?

Sean
  • 442
  • 3
  • 6
  • 19
  • you are also showing partial code.. why are you not posting and or showing all relevant code..? what is `a` where is `a` defined..? etc... do a simple google search on `OpenFileDialog` there are tons of working examples on the internet as well as on `SO` also google the function `File.ReadAllLines` – MethodMan Nov 16 '15 at 15:02
  • 2
    You can use the _FileName_ property of the _OpenFileDialog_ and store the obtained file name in a variable. So, while you know the file name, you can open it whenever you want... – Stas Ivanov Nov 16 '15 at 15:04
  • a is string ... i forgot to write it – Zaid Jassim Nov 16 '15 at 15:08
  • [OpenFileDialog() MSDN](https://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog(v=vs.110).aspx) – MethodMan Nov 16 '15 at 15:10

2 Answers2

0

Try something like this

var openDialog = new OpenFileDialog();
if (openDialog.ShowDialog == DialogResult.OK)
{
    using (var stream = File.OpenRead(openDialog.FileName)
    {
        //read everything here
    }
}
msnw
  • 93
  • 7
  • OpenFileDialog pic = new OpenFileDialog(); pic.ShowDialog(); string a; System.IO.StreamReader file = new System.IO.StreamReader(pic.OpenFile()); while ((a = file.ReadLine()) != null) { //mycodes } //here I want to read again from same file – Zaid Jassim Nov 16 '15 at 15:11
-1

My guess is that the file only contains 1 line and so once you've read it there's nothing left to read. If you want to read the same line again you'll need to close the file and open it again. You should also be using a 'using' statement around the stream reader to ensure it is correctly disposed of, so something like:

string a = string.Empty;
using(StreamReader reader = new StreamReader(pic.FileName))
{
  a = reader.ReadLine();
}
C. Knight
  • 739
  • 2
  • 5
  • 20
  • this is only for one line i have for loop for every line – Zaid Jassim Nov 16 '15 at 15:08
  • but after i finished reading in for loop and make some processing I want to read from same file again ... so I have it just readline but it's tell me it's empty ... so I jast want to read from it again – Zaid Jassim Nov 16 '15 at 15:10
  • Simply place a for loop inside the 'using' statement then. The issue wasn't around that - nor was my example meant to show that - the issue was that you were reading to the end of a file. You then need to close it and open it again. If you write another identical using statement below the one I showed you will read from the beginning of the file again... – C. Knight Nov 16 '15 at 15:35