3

My application opens a NetworkStream and a StreamWriter to sent HL7-messages to a service. This service receives the HL7-messages and ALWAYS sends back an acknowledgement. I have the following problem: After sending the HL7-messages (which works, I tested it) I try to use s StreamReader to receive the acknowledgement from the service but this leads to an argument exception "The datastream was not readable". I debugged into my code and found out that the connection was closed after the using-block of the StreamWriter and therefore there is nothing to read for the StreamReader.

Here is my code:

    public static void SendMessage(string message, string ip, int port)
    {
        string acknowledge;

        try
        {
            using (TcpClient client = new TcpClient(ip, port))
            {
                using (NetworkStream networkStream = client.GetStream())
                {
                    using (StreamWriter clientStreamWriter = new StreamWriter(networkStream))
                    {
                        clientStreamWriter.Write(message);
                    }

                    using (StreamReader clientStreamReader = new StreamReader(networkStream))
                    {
                        acknowledge = clientStreamReader.ReadToEnd();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Connection Problems: " + ex.ToString()); 
        }
    }

How can I stop the connection from being closed, because I want to read the acknowledgement the client sends back after receiving the HL7-messages ?

Paul Weiland
  • 727
  • 10
  • 24
  • 1
    possible duplicate of [Is there any way to close a StreamWriter without closing it's BaseStream?](http://stackoverflow.com/questions/2666888/is-there-any-way-to-close-a-streamwriter-without-closing-its-basestream) – Ondrej Svejdar Sep 01 '14 at 11:09

1 Answers1

4

Solved: StreamWriter inside the using block also closed the base Stream.

Solution: Tell the Streamwriter to leave connection open.

public StreamWriter(
    Stream stream,
    Encoding encoding,
    int bufferSize,
    bool leaveOpen
)
Paul Weiland
  • 727
  • 10
  • 24