I assume you are using the SerialPort class in the System.IO.Ports
namespace. If not, you might want to look at that.
You might want to consider a MemoryStream instead of a List<byte> to
store the bytes. A MemoryStream will store the bytes as well and allocate
new memory when you need it, but if the message is large, then you can call
the GetBuffer method on the stream to get the internal buffer, whereas with
List<byte> you have to create a new array, and that might be expensive.
Once you have the byte array, you can pass it to the GetString method on
the encoding in one shot, passing the array, as well as the start index and
number of characters to process. This will help in the case of using the
MemoryStream, since you can get the buffer directly and then tell the
encoder just how much to process.
It would be nice if you could use the StreamReader here to perform the
encoding for you, but unfortunately, it buffers the characters from the
stream internally, and if the device isn't going to offer up anything past
the message that it sent, the StreamReader will hang.
Hope this helps.
<ca******@gmail.com> wrote in message
news:11*********************@g14g2000cwa.googlegro ups.com...
I am getting a packet of data from an instrument. The strings in the
data packet are null terminted. What is the best way to extract a
string from the data packet?
I am working in .Net 20.
Presently the code reads byte by byte through the packet adding the
value into a List<byte>. The a new byte[] is created based on the
count of the List<byte>. The code iterates though the List<byte> to
populate the byte[]. Finally the byte[] is passed to an instance of
Encoding to get the string.
Is there a better way which does not require looping thourgh the string
twice?