SerialPort Vs MSComm
Is it possible that .Net SerialPort and VB6 MSComm work different?
In both cases, I´m reading data from the buffer, and both go开发者_StackOverflow中文版t 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();
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.
I expect that they both use the underlying O/S API; but I guess that they may each use that API in difference ways: e.g. with different default COM port parameters (if you don't specify the parameters explicitly).
Another difference may be in the timing: when you read the input/reply, how do you know whether it's been sent yet, and how do you know whether the 'read' or 'input' function is waiting for long enough?
MSComm and Serialport are free gifts and have not many in common. A well known portable library that spares you from the troubles is SuperCom. It offers a MSComm compatible ActiveX and also a A NET class library. One can use the one that fits better. It can be used with C++, Delphi, VB6, VB net, C#, FreePascal, Perl, Java, and many more. And it is fully compatible to 32 bit and 64 bit of Windows incl. Windows XP,7,8,10.
精彩评论