SerialPort Vs MSComm

Rama picture Rama · Jan 27, 2011 · Viewed 9.7k times · Source

Is it possible that .Net SerialPort and VB6 MSComm work different?

In both cases, I´m reading data from the buffer, and both got me different strings, if I import the MSComm dll into my .Net project, It works perfectly (obviously).

Does anyone have more in deep information?

If it helps, here are my to simple samples, in both cases I send the same Byte Array...

VB6:

Dim MSComm1 As Object
Dim ArrToSend() As Byte
Dim IncomeData As String
Set MSComm1 = CreateObject("MSCommLib.MSComm")
With MSComm1
    .CommPort = 1
    .PortOpen = True
End With

ReDim ArrToSend(4)
ArrToSend(0) = 179
ArrToSend(1) = 1
ArrToSend(2) = 92
ArrToSend(3) = 92
MSComm1.Output = ArrToSend
IncomeData = MSComm1.Input

c#

SerialPort _serialPort = new SerialPort();
_serialPort.Open();
Byte[] _bytesToSend = new Byte[4];
_bytesToSend[0] = 179;
_bytesToSend[1] = 1;
_bytesToSend[2] = 92;
_bytesToSend[3] = 92;
_serialPort.Write(_bytesToSend, 0, _bytesToSend.Length);
String ReadExisting = _serialPort.ReadExisting();

Answer

Hans Passant picture Hans Passant · Jan 27, 2011

You are mixing bytes and strings. MSComm was very lax about it but SerialPort cares about text encoding. Clearly you are using a binary protocol, it is likely that your received string is containing question marks for bytes that could not be converted to the SerialPort.Encoding (default is ASCII). You have to use the Read() method to get the response.