2011-12-16 94 views
1

我正在寻找一种从networkStream对象读取单个字符的有效方法。 With NetworkStream.Read方法可以读取一个数组字节而不是单个字符。如何从C#中的NetworkStream对象读取单个字符?

这里是我已经试过,但我得到了越来越字符

public char readChar(NetworkStream networkStreamObj) 
    { 
     byte[] bytesArray = new byte[8129]; 
     int n = networkStreamObj.Read(bytesArray, 0, bytesArray.Length); 
     char[] charArray = new char[Encoding.ASCII.GetCharCount(bytesArray, 0, n)]; 
     /**Need help after this line**/ 
    } 

请注意,我试过另一种选择使用StreamReader对象,但我得到的错误说,流是不可读的一个阵列中后卡住。

回答

1

既然你正在阅读ASCII,所有你需要的是:

int byte = stream.ReadByte(); 
if(byte < 0) // hadle EOF 
else return (char) byte; 

在更一般的情况下,当编码可能是多字节,你应该使用TextReader的,例如一个StreamReader。这是设计的来处理来自流的文本读取(通过任意的Encoding)。

即使用UTF-8

using(var reader = new StreamReader(stream, Encoding.UTF8)) { 
    ... consume the class 
} 

int next = reader.Read(); 
if(next < 0) // handle EOF 
else { 
    char c = (char)next; 
    // ... 
} 
+0

马克嗨!有了streamReader,我得到了一个异常错误“Stream was unreadable”!这个错误的原因是什么? – Xris 2011-12-16 07:10:35

相关问题