user43051
user43051

Reputation: 345

C# - stream reader issue

so basically i'm developing a networking program in c# and I'm trying to send a string from the server to the client using stream reader but I'm having a very strange issue. When I use this code...

[Server Side]

foreach (DataRow row in StocksTable.Rows)
            {
                stocks += row["description"] + "," + row["buy"] + "," + row["sell"] + ",";
            }

[Client]

textBox3.Text = streamReader.ReadLine();

... it works but it only returns the first row. When I change the "\n" with ";" for example so that everything is on one row, the client crashes.

I tried using an iterator to print all the rows but it doesn't work as well.

I know it sounds funny and probably there's some simple explanation but I've been stuck on this for a while and i'm getting confused.

EDIT:

I tried iterating and this thing works:

for (int i = 0; i < 5; i++)
            {
                textBox3.Text += streamReader.ReadLine();
            }

(5 is the number of rows in the string)

but this doesn't:

while (true)
            {
                string s = streamReader.ReadLine();
                if (s != null)
                {
                    textBox3.Text += s;
                }
                else
                {
                    break;
                }
            }

Upvotes: 2

Views: 275

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You should use the StreamReader.ReadToEnd() in order to read all the lines. ReadNextLine will only read a line and stop at a \n character.

If you iterate, you should check if more content is still available.

Upvotes: 2

Erik Philips
Erik Philips

Reputation: 54618

I'm going to assume that stocks is a string. A string can contain many lines (lines defined as string delimited by a CR, LF, or CRLF). In this case it appears you are creating multiple lines in the string by using \n. There for:

textBox3.Text = streamReader.ReadLine();

Will read the first Line in the stream.

Upvotes: 2

Related Questions