C# – How to set the ReadBufferSize on .NET serial port

cserial-portvb.net

So, I am creating a VB.NET program that listens to a serial port. I was using this

Dim WithEvents ptr_SerialPort As System.IO.Ports.SerialPort
...
 ptr_SerialPort = My.Computer.Ports.OpenSerialPort(serialportname, baudrate,parity, databits, stopbits)

which worked fine until i realized that I am overrunning my SerialPort.ReadBufferSize property, which is 4096, and losing data:

https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize(v=vs.110).aspx

So I tried to increase the size of the buffer as follows

ptr_SerialPort = My.Computer.Ports.OpenSerialPort(serialportname, baudrate, parity, databits, stopbits)
ptr_SerialPort.ReadBufferSize = 2000000

But I get the error "can't set the buffer size while it's open". Which is reasonable, so I tried this:

ptr_SerialPort = New System.IO.Ports.SerialPort(serialportname, baudrate, parity, databits, stopbits)
ptr_SerialPort.ReadBufferSize = 2000000
ptr_SerialPort.Open()

Well, this results in a Serial port that does NOT receive data… I guess that My.Computer.Ports.OpenSerialPort is doing more than just instantiating it, and what I have above is a serial port object that is not connected to my hardware. So, my question is… how do I open a serial port on my PC, and specify the ReadBufferSize property??

Thanks very much!

Best Answer

Well, oddly

ptr_SerialPort = New System.IO.Ports.SerialPort(serialportname, baudrate, parity, databits, stopbits)
ptr_SerialPort.ReadBufferSize = 2000000
ptr_SerialPort.Open()

is now working... so this is the way to do it after all. It must have been some intermittent problem on the other end that fooled me. Thanks for the answers, sorry to take your time.