473,224 Members | 1,977 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,224 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 4550
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...
1
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
0
by: veera ravala | last post by:
ServiceNow is a powerful cloud-based platform that offers a wide range of services to help organizations manage their workflows, operations, and IT services more efficiently. At its core, ServiceNow...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: mar23 | last post by:
Here's the situation. I have a form called frmDiceInventory with subform called subfrmDice. The subform's control source is linked to a query called qryDiceInventory. I've been trying to pick up the...
2
by: jimatqsi | last post by:
The boss wants the word "CONFIDENTIAL" overlaying certain reports. He wants it large, slanted across the page, on every page, very light gray, outlined letters, not block letters. I thought Word Art...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....

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.