Take the 2-minute tour ×

how can I send a multiline string with blank lines over a NamedPipe?

If I send a string

string text= @"line 1 

line four
StreamWriter sw = new StreamWriter(client);

I get on the server side only "line 1":

StreamReader sr = new StreamReader(server);
string message = sr.ReadLine();

When I try something like this

StringBuilder message = new StringBuilder();
string line;
    message.Append(line + Environment.NewLine);

he is hanging in the loop while the client is connectet and only release when the client diconnecting.

Any ideas how I can get the whole string but not hanging in this loop? I need to to process the string and return it on the same way to the client. It's important that i hold the original formatting of the string including blank lines and whitespaces.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

StreamReader is a line-oriented reader. It will read the first line (terminated by a newline). If you want the rest of the text, you have to issue multiple readlines. That is:

StreamReader sr = new StreamReader(server);
string message = sr.ReadLine(); // will get "line1"
string message2 = sr.ReadLine(); // will get "line2"

You don't want to "read to end" on a network stream, because that's going to hang the reader until the server closes the connection. That might be a very long time and could overflow a buffer.

Typically, you'll see this:

NetworkStream stream = CreateNetworkStream(); // however you're creating the stream
using (StreamReader reader = new StreamReader(stream))
    string line;
        // process line received from stream

That gives you each line as it's received, and will terminate when the server closes the stream.

If you want the reader to process the entire multi-line string as a single entity, you can't reliably do it with StreamReader. You'll probably want to use a BinaryWriter on the server and a BinaryReader on the client.

share|improve this answer
Using BinaryWriter(string message) and BinaryReader(string message) works like a charm. Thank you! –  mc-kay Dec 10 '10 at 21:02
add comment

Why not just call ReadToEnd() on StreamReader?

StreamReader sr = new StreamReader(server);
string message = sr.ReadToEnd();
share|improve this answer
Same effect, he only release when the client is diconnecting. –  mc-kay Dec 10 '10 at 20:01
add comment

Your Answer


