简体   繁体   中英

Unable to read character from a networkStream object using StreamReader in C#

I want to read an array of character from a networkStream object in this way :

    public String readLine(NetworkStream networkStream)
    {
        using (StreamReader reader = new StreamReader(networkStream))//This line throws an exception
        {

            char[] buffer = new char[128];
            int offset = 0;
            int ch;

            while(true)
            {
                ch = reader.Read();
                if (ch == -1 || ch == '\n')
                {
                    break;
                }
                else if (ch == '\r')
                {
                    //int tempch = ;
                    if (reader.Peek()== '\n')
                    {
                        break;
                    }
          }
      }

When i run the program i get an exception error "Stream unreadable" . Is it because the StreamReader constructor expects a stream Object not a networkStream as a parameter ? If yes, is there a workaround or an alternative way of reading characters from a networkStream object?

You'll get this exception when the stream's CanRead property is false. We can't tell how you created the NetworkStream, but a logical explanation is that you're trying to read from a network stream that you opened for writing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM