-1

I have a client which talks to a server, the code below is supposed to print on the console what was typed in - this spans over multiple lines.

The problem is that it displays all the lines, then throws an exception.

I have tried different ways in order to get this to work such as peek() which causes the final line to be cut off and the same exception to be thrown.

Is there something I am missing?

using (sr)
{
    try
    {
        while (!sr.EndOfStream)
        {
        Console.WriteLine(sr.ReadLine());
        }
    }
    finally
    {
    sr.Close();
    }
}

The exception is: System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

I have used .ReadTimeout and .WriteTimeout just before the using (sr)

jjharvey
  • 15
  • 6
  • 1
    Side note: you don't need try/finally/close if you have a using block. – Dai Feb 23 '15 at 23:26
  • Please check if this is not something related to your problem: http://stackoverflow.com/questions/1450263/c-sharp-streamreader-readline-does-not-work-properly – Wiktor Stribiżew Feb 23 '15 at 23:36
  • 1
    where is the rest of your `sr` assignment? it should all be in the using statement (see https://msdn.microsoft.com/en-us/library/yh598w02.aspx for `using` best practices) – Rufus L Feb 24 '15 at 00:20
  • so what timeouts did you set? show us the whole block of code. i'm presuming network conditions are actually causing your read to not complete, just like the exception says. – John Gardner Feb 24 '15 at 01:36

1 Answers1

1

Without more context this will be incredibly difficult to troubleshoot. Your issue could stem from:

  • Permission: The file may not be accessible via the application.
  • Invalid File-Type to be read.
  • Issue between client and server.

There are quite a few variables, without more context. However, you could attempt the following:

using(var reader = new StreamReader(...))
{
     string line;
     while((line = reader.ReadLine()) != null)
           Console.WriteLine(line);
}

If that works, then it could be an issue between the while(!reader.EndOfStream) dumping out the contents line by line to your console.

If you provide more context hopefully we can assist better.

Important: I notice in your using in which you declare your StreamReader, you don't actually designate the file for it to read. Which would throw an exception, so you may want to actually add that in your example as well.

Your raw IOException could only generate one of the following:

  • DirectoryNotFoundException
  • EndOfStreamException
  • FileNotFoundException
  • FileLoadException
  • PathTooLongException

Which should help you identify your problem as well.

Greg
  • 11,302
  • 2
  • 48
  • 79