473,387 Members | 1,592 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

streamReader & StreamWriter understanding

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
--
The Matrix Insurrection
Nov 16 '05 #1
9 4557
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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);
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
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

"Jon Skeet [C# MVP]" wrote:
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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);
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #3
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
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();
}

}

"Jon Skeet [C# MVP]" wrote:
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #5
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
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!

"Jon Skeet [C# MVP]" wrote:
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #7
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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)?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
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.
"Jon Skeet [C# MVP]" wrote:
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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)?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #9
ShadowOfTheBeast <Sh**************@discussions.microsoft.com> wrote:
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 :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Joecx | last post by:
Using vb.net, I am using Streamreader to read a text file and searching for a line to delete, the I close the file and open it as a streamwriter so I can put the new file back to disk without the...
1
by: andrewcw | last post by:
OK I am half way there - I can manipulate the stream without the byte issue like this - but is this the way to push the new values back into the stream & write out the stream without resorting to...
6
by: Jimbo | last post by:
After I read or write a file with streamreader and streamwriter and I close it with the Close method, does that automatically let go of the file so that any other process can modify it? In my...
4
by: Astronomically Confused | last post by:
using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; class HttpProcessor { private Socket s;
1
by: R.L. | last post by:
See the code below, var 'content ' is suppose to be "Hello!", not "". Who knows why? Thanks ---------------------------------------- string text = "hello!"; MemoryStream stream = new...
1
by: Rob T | last post by:
Hi, I have a simple little program that I'm going to use to access our SMTP server. The below code works perfectly fine, but my question is if I were to try to execute the last line...
16
by: vvenk | last post by:
Hello: When I use either one to read a Text file, I get the same result. The length of the string that the file's content has been written into is the same. However, if the file is binary,...
11
by: LucaJonny | last post by:
Hi, I've got a problem using StreamReader in VB.NET. I try to read a txt file that contains extended characters and theese are removed from the line that is being read. I've read a lot of...
3
by: stumorgan | last post by:
I'm doing some USB communications in C# and am running into a minor annoyance. I'm using the Windows API CreateFile function to get a SafeFileHandle, which I then stuff into a FileStream and from...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.