Himanshu Singh
Himanshu Singh

Reputation: 84

Length = 'serverStream.Length' threw an exception of type 'System.NotSupportedException'

I am trying to create a socket coonection with the server. For that I am passing an xml and it is stored in the string ngconnect. Now while debbuging the code I found the exception in serverstream.Write as

'serverStream.Length' threw an exception of type 'System.NotSupportedException'

What may be the reason of such an exception and how do I remove them.

        private void button1_Click(object sender, EventArgs e)
        {
            portadd = textBox2.Text;

            ip = textBox1.Text;
            port = Convert.ToInt32(portadd);
            clientSocket.Connect(ip, port); 
            NetworkStream serverStream = clientSocket.GetStream();
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes(ngconnect);
            serverStream.Write(outStream, 0, 200);
            serverStream.Flush();

            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);
            msg(returndata);
            textBox3.Focus();

    }

Upvotes: 1

Views: 3153

Answers (1)

C.Evenhuis
C.Evenhuis

Reputation: 26446

If I'm correct, the application did not throw the exception, but you were debugging, inspected serverStream and saw the exception in the debugger.

This is normal behavior - Visual Studio attempts to show all property values, and NetworkStream does not support the Length property. See the MSDN for more information:

NotSupportedException: A class derived from Stream does not support seeking.

You can inspect the CanSeek property of any Stream to verify whether it supports seeking, and so the Length property.

Upvotes: 1

Related Questions