blah blah blah is here! blah blah » Close

up1down
link

i'm reading a rs232 port and i call the readexisting:

string x = port.ReadExisting();
string y;

if(x.Contains("\r"))
{
do something;
}
else
{
y = x + port.ReadExisting();
}

this doesn't keep looping. i want it to keep reading the port and concatenating the string until the port sends a "\r" character. how should i do this?

last answered one year ago

2 answers

link

thanks vulpes, i used a while loop.

string received = serialPort.ReadExisting();
int y = received.IndexOf("\r");
while(y ==-1)
{
received = received + serialPort.ReadExisting();
y = received.IndexOf("\r");
}

up1down
link

I'd just use port.ReadLine() which will block until (by default) "\r\n" is received.

If you're only expecting "\r" then change the port's NewLine property to that.

ReadLine() doesn't return the Newline characters themselves but they are removed from the input buffer.

To avoid blocking indefinitely, you can set the port's ReadTimeout property to a reasonable value and catch the resulting TimeoutException:

port.NewLine = "\r"; // if it's not \r\n
port.ReadTimeout = 1000; // 1 second say
string y = "";

try
{
y = port.ReadLine();
}
catch (TimeoutException)
{
MessageBox.Show("Time out occurred");
}

Feedback