StreamReader.EndOfStream produces IOException
- by Ziplin
I'm working on an application that accepts TCP connections and reads in data until an </File> marker is read and then writes that data to the filesystem. I don't want to disconnect, I want to let the client sending the data to do that so they can send multiple files in one connection.
I'm using the StreamReader.EndOfStream around my outter loop, but it throws an IOException when the client disconnects. Is there a better way to do this?
private static void RecieveAsyncStream(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient client = listener.EndAcceptTcpClient(ar);
// init the streams
NetworkStream netStream = client.GetStream();
StreamReader streamReader = new StreamReader(netStream);
StreamWriter streamWriter = new StreamWriter(netStream);
while (!streamReader.EndOfStream) // throws IOException
{
string file= "";
while (file!= "</File>" && !streamReader.EndOfStream)
{
file += streamReader.ReadLine();
}
// write file to filesystem
}
listener.BeginAcceptTcpClient(RecieveAsyncStream, listener);
}