streamReader & StreamWriter understanding

G

Guest

Hi, I have got a major headache understanding streamReader and streamWriter
relationship.
I know how to use the streamreader and streamwriter independently.
but how do you write out using the streamwriter, what you have read into a
streamReader? and also can someone explain how they work in simple terms
 
J

Jon Skeet [C# MVP]

ShadowOfTheBeast said:
Hi, I have got a major headache understanding streamReader and streamWriter
relationship.
I know how to use the streamreader and streamwriter independently.
but how do you write out using the streamwriter, what you have read into a
streamReader? and also can someone explain how they work in simple terms

I'm not entirely sure what you mean. Could you give a concrete example?
Usually you'd just do something like:

string line;
while ( (line = reader.ReadLine()) != null)
{
writer.WriteLine (line);
}
 
G

Guest

hi Jon,
thanks for replying me...this is part of my code

i have a streamwriter that writes my string (stringbuilder) into a stream
and a streamreader that gets the response from the stream now the problem i
have is
after reading the stream and printing it out using the line in the code:

Console.WriteLine( sr.ReadToEnd() );

how do i write the text to a file..i cant seem to achieve that as you will
see i have a test code below which i have been trying to use to do this
normally it might work if it was just reading and writing froma file but the
streamreader is getting a httpResponseStream...but even then it prints out
using console.writeline as displayed above and in code but when i use another
streamwriter to try and write the text to a file it does not work ...but if i
use the same new stream writer to write an arbitrary text it works as
demonstrated in my test code area and again below:

//fileWriter.Write(sr.ReadToEnd()); //THIS LINE DOES NOT WORK
fileWriter.Write("this is annoying");//BUT THIS LINE WORKS..WHY??

p.s some code needs uncommenting for the test code to work



StreamWriter sw = new StreamWriter( httpRequest.GetRequestStream() );
sw.Write( sbuilder.ToString() );
sw.Close();

HttpWebResponse httpResponse = ( HttpWebResponse )httpRequest.GetResponse( );


StreamReader sr = new StreamReader( httpResponse.GetResponseStream() );
Console.WriteLine( sr.ReadToEnd() );




///Test code area
///write file
////////////////////////////////////////////////////////////////////////
StreamWriter fileWriter = new StreamWriter("OutputTestfile.txt");

/////////////////////////////////////////////////////////////////////
///write to the stream object
////////////////////////////////////////////////////////////////////////

//fileWriter.Write(sr.ReadToEnd()); //THIS LINE DOES NOT WORK
fileWriter.Write("this is annoying");//BUT THIS LINE WORKS..WHY??
////////////////////////////////////////////////////////////////////////
///close stream
///////////////////////////////////////////////////////////////////////
fileWriter.Close();
///////////////////////////////////////////////////////////////////////
/// end test code area




sr.Close();
httpResponse.Close();

thanks
 
J

Jon Skeet [C# MVP]

ShadowOfTheBeast said:
thanks for replying me...this is part of my code

i have a streamwriter that writes my string (stringbuilder) into a stream
and a streamreader that gets the response from the stream now the problem i
have is
after reading the stream and printing it out using the line in the code:

Console.WriteLine( sr.ReadToEnd() );

If that works, then a simple StreamWriter.Write should work fine too.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
G

Guest

hi jon,
here is a simple class that demonstrate what i am trying to achieve and this
works!
although my streamreader here reads from a file but the one i am reading
from in the original program reads a HttpResponse.GetResponseStream()...but
it should still work as the console.write does display the text...the second
streamwriter just does not write to file

class Class1
{
private const string FILE_NAME = "testfile.txt";
private const string FILE_NAME2 = "MyFileOutput.txt";

/// <summary>
/// The main entry point for the application.
/// </summary>
///
[STAThread]
static void Main(string[] args)
{

// if (File.Exists(FILE_NAME))
// {
// Console.WriteLine("{0} already exists.", FILE_NAME);
// return;
// }

StreamReader sr = new StreamReader(FILE_NAME);

string strtext;


StreamWriter sw = new StreamWriter(FILE_NAME2);

if( (strtext = sr.ReadToEnd()) != null)
{
Console.WriteLine("strtext is " + strtext);
sw.WriteLine(strtext);

}
else
{
Console.WriteLine("something is wrong!");
}



//close stream reader and writer
sr.Close();
sw.Close();
}

}
 
J

Jon Skeet [C# MVP]

ShadowOfTheBeast said:
hi jon,
here is a simple class that demonstrate what i am trying to achieve and this
works!
although my streamreader here reads from a file but the one i am reading
from in the original program reads a HttpResponse.GetResponseStream()...but
it should still work as the console.write does display the text...the second
streamwriter just does not write to file

Hang on - in the code which is failing, are you calling ReadToEnd twice
(once for the console, and once to write)? If so, that's the problem -
you can only read the contents once.
 
G

Guest

thanks a lot Jon it works flawlessly now you were right..i am still not very
well versed on streamreaders and writers they seem alittle quirky to me as
this refined code demonstrates in terms of where in the code you declare your
Stream Readers and Streamwriter objects...pay particular attention to the
lines with Capital letters comments...

--------other codes--------------

StreamReader sr = new StreamReader( httpResponse.GetResponseStream() );

string strtext;
//StreamWriter fileWriter = new StreamWriter("OutputTestfile.txt");//THIS
CAUSES AN ISSUE HERE AS REGARDS TO...

//Console.WriteLine(strtext = sr.ReadToEnd());

//write to file
StreamWriter fileWriter = new
StreamWriter("OutputTestfile.txt");//...PLACING IT HERE,WORKS HERE FINE.

//write to the stream object...essentially the outputfile
fileWriter.Write(strtext);

//close stream objects
fileWriter.Close();
sr.Close();

}





i dont know why it does this ...but my code works and i am happy...i might
investigate it once i know more about streamreaders and writers...if its
something you can see and i seem blind please point it out to me...once again
cheers!
 
J

Jon Skeet [C# MVP]

ShadowOfTheBeast said:
thanks a lot Jon it works flawlessly now you were right..i am still not very
well versed on streamreaders and writers they seem alittle quirky to me as
this refined code demonstrates in terms of where in the code you declare your
Stream Readers and Streamwriter objects...pay particular attention to the
lines with Capital letters comments...

--------other codes--------------

StreamReader sr = new StreamReader( httpResponse.GetResponseStream() );

string strtext;
//StreamWriter fileWriter = new StreamWriter("OutputTestfile.txt");//THIS
CAUSES AN ISSUE HERE AS REGARDS TO...

//Console.WriteLine(strtext = sr.ReadToEnd());

//write to file
StreamWriter fileWriter = new
StreamWriter("OutputTestfile.txt");//...PLACING IT HERE,WORKS HERE FINE.

//write to the stream object...essentially the outputfile
fileWriter.Write(strtext);

//close stream objects
fileWriter.Close();
sr.Close();

}

That seems very odd - I can't see any reason for that to cause any
difference. Do you have a complete program which always lets you
reproduce the problem (and which always works again when you *just*
move a line of code)?
 
G

Guest

Hi Jon,
here is a relatively short and complete code i have added comments to where
the error occurs in uppercase letters :

class Class1
{
private const string FILE_NAME = "MyInputfile.txt";
private const string FILE_NAME2 = "MyOutputfile.txt";

/// <summary>
/// The main entry point for the application.
/// </summary>
///
[STAThread]
static void Main(string[] args)
{

// if (File.Exists(FILE_NAME))
// {
// Console.WriteLine("{0} already exists.", FILE_NAME);
// return;
// }

StreamReader sr = new StreamReader(FILE_NAME);

string strtext;

//TO GET THE RUNTIME ERROR UNCOMMENT THE //** CODE LINE AND COMMENT THE
LINE BELOW IT

//**StreamWriter sw = new StreamWriter(FILE_NAME2);//IF THIS STREAM IS
FULLY CREATED HERE THEN I GET A RUNTIME ERROR!
//WITH REGARDS TO.....

StreamWriter sw = null;//IF THIS STREAM DECLARED HAS NOT BEEN ASSINGED TO
A NEW OBJECT YET OR HAS BEEN ASSINGED NULL

//can define and assign my string immediately on the line below
strtext = sr.ReadToEnd();
//--------------OR---------
// if ((strtext = sr.ReadToEnd()) != null)
// {
// Console.WriteLine("stream is not null...\nhence Stream has been read ");
// }

//if file exists open and append text to it
if (File.Exists(FILE_NAME2))
{
sw = File.AppendText(FILE_NAME2);// add a \n for new appended text

//display strtext in console
Console.WriteLine(strtext);

//give timestamp
// sw.Write(DateTime.Now);

//Write to file
// sw.Write("......");//write or writelineis the key

sw.WriteLine(strtext); //find how to add a "\n" in notepad..done
automatically nice!!!!


//write out all in underlying stream
sw.Flush();//test it 2morrow...checked already check it tommorow
}
else
{
//assign Stream sw to a new object stream
sw = new StreamWriter(FILE_NAME2);

//give timestamp
// sw.Write(DateTime.Now);

//Write to file
// sw.Write("......");//write or writelineis the key

//Write to file
sw.WriteLine(strtext);

}




//close stream reader and writer
sr.Close();
sw.Close();

hi jon i found the problem with the //** code line ...its because i had
acreated and assigned my StreamWriter sw to a new object ...and yet within
my if statement i try to assign it to a File.Append() method.Silly Me!!!
thanks for your help i really appreciate it. thanks hope we come across each
other on the postings again! cheers.
 
J

Jon Skeet [C# MVP]

ShadowOfTheBeast said:
here is a relatively short and complete code i have added comments to where
the error occurs in uppercase letters :

<snip>

I'm glad you found the problem. Next time you come up with a short but
complete program, though, it's worth trying to cut and paste then
compile it - using statements and the end of the method and class would
help :)
 

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

Top