Simple question. How to read/write from/into stream.

  • Thread starter Thread starter John Demigor
  • Start date Start date
J

John Demigor

Hi,

I have an integer value I need to read/write as 4 bytes from/into Stream
(NetworkStream), but I cannot find ReadInt/WriteInt method in the Stream
class.
The same problem with string.

Thanks in advance
 
Good hint, thanks. Now the question, how to write string in stream in ANSI
(single-byte) format?
 
You should use the Write overloaded method of signature:
Write ( byte [] data, int start, int length )
To that method you should supply a byte array which you have created by
calling
System.Text.Encoding.[YOUR_PREFERRED_ENCODING].GetBytes("Your string");

So, something like:
string text = "Happy weekend!";
BinaryWriter bw...;
byte [] data = System.Text.Encoding.ASCII.GetBytes(text);
bw.Write(data, 0x0, data.Length);
 
John Demigor said:
I have an integer value I need to read/write as 4 bytes from/into Stream
(NetworkStream), but I cannot find ReadInt/WriteInt method in the Stream
class.

Use a BinaryWriter.
The same problem with string.

Again, you can use BinaryWriter - but be careful of Write(string) as
this adds an encoded version of the string length before the string
itself. Use Encoding.GetBytes to get the bytes and write them if you
need to. Alternatively, if this is in a different stream, construct a
StreamWriter which is designed for writing text.
 
Thanks,
System.Text.Encoding.[YOUR_PREFERRED_ENCODING].GetBytes("Your string");

My preferred encoding is usually ISO-8859-1, but it would be great to use
windows system codepage.
How does it go then?
 
You should look at the GetEncoding method if you want some other encoding
than
those that are predefined.
Have a look at:
http://msdn.microsoft.com/library/d...fsystemtextencodingclassgetencodingtopic2.asp

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
John Demigor said:
Thanks,
System.Text.Encoding.[YOUR_PREFERRED_ENCODING].GetBytes("Your string");

My preferred encoding is usually ISO-8859-1, but it would be great to use
windows system codepage.
How does it go then?
 
John Demigor said:
System.Text.Encoding.[YOUR_PREFERRED_ENCODING].GetBytes("Your string");

My preferred encoding is usually ISO-8859-1, but it would be great to use
windows system codepage.
How does it go then?

Use Encoding.Default - and note that it's *not* the default for things
like StreamReader if you don't specify the encoding. It should really
be called something like Encoding.WindowsSystemDefault.
 
Back
Top