newb question - Manipulating Text Files

  • Thread starter Thread starter grif
  • Start date Start date
G

grif

hey everyone!

In amongst my C# learning i'm starting to fiddle around with some basic code
on stuff that interests me. So I decided to write a really simple console
app that basically opens and reads the first line of a text file and then
saves the result to a variable.

Well clearly i'm so lame and new that i'm having trouble actually assigning
the result to a variable lol :)

So here is the guts of what I wrote initially

// *** silly text reader program ***

// Open the file for reading
StreamReader tr = File.OpenText("url.txt");

string read = null;
while ((read = tr.ReadLine()) != null)
{
Console.WriteLine(read);
}

// assign result to variable
string url = tr.ReadLine();

// close the stream
tr.Close();

//print variable contents
System.Console.WriteLine("the current url is:{0}", url);

// *** end program

So does anyone have a n idea of where i'm going wrong....the variable in
fact appears to be empty when I print its stored value. So the program is
working as such but I just cant get the data into it. I know this is sort of
over my head a little at this stage but I just wanted to have a fool
around...and I HATE when things dont work lol :)

Cheers
griff
 
Taking a quick glance at your code, I think...
Console.WriteLine(read);

...will print all the lines that can be read from the stream to the
console (including the first line). If you then later state...
string url = tr.ReadLine();

....then the stream is still at the end of the file and will probably
return null. So 'url' is null too.

Perhaps you can remove the whole 'read' variable and corresponding
'while' loop?
 
Its allright I fixed it....it was something really simple...I was trying to
assign tr.ReadLine(); to the URL variable when in fact I should have just
string url = read;

That explains why it was just printing out an empty variable...because
Readline was re-running and getting the next line which is empty etc

Silly mistake and something I should have picked up...its funny when you
just cant see your own cockups lol :)

Cheers Guys
 
Its allright I fixed it....it was something really simple...I was trying to
assign tr.ReadLine(); to the URL variable when in fact I should have just
string url = read;

That explains why it was just printing out an empty variable...because
Readline was re-running and getting the next line which is empty etc

Silly mistake and something I should have picked up...its funny when you
just cant see your own cockups lol :)

Cheers Guys
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top