StephanJW
StephanJW

Reputation: 177

C# Comport - Possible Loss of Data

I have been trying to troubleshoot an issue and I really don't have any thoughts as to go about resolving the following problem:

I have a software application that is able to listen for a device that is capable of uploading data to a computer. Once this data is captured, it is written to a text file and stored for later use.

void DataRecieved(object sender, EventArgs e)
{
   while ((bufferedData = comport.ReadLine()) != null)
   {
       uploadedData += bufferedData + Environment.NewLine;
   }

   comport.Close();

   System.IO.StreamWriter writeUploadedPro = new System.IO.StreamWriter(uploadFilePath);
   writeUploadedPro.Write(uploadedData);
   writeUploadedPro.Close();

   isUploadComplete = true;
}

I can establish, recieve, and verify a connection, and what I have programmed does indeed produce a text file of the uploaded data, however the data is contains is not complete.

Example:

%
N0?77??.5???3
G0? X3.??? Z4.5??6 
Z5.?? 
?3.5?76 
G01 Z5.?? 
Z4.9471 
X?.?3 Z4.???9 
Z?.???6 
?3.?? Z?.??? 
Z4.???? 
X3.7??4 
G?? X3.???? ?4.5??6 
M30
?

It has numerous '?' which either should be a letter or digit. I have reaffirmed that the settings I have for the comport (Baud, Data, Stop, Parity, Handshake, and COM name are correctly specified). I have also tried setting the ReadBufferSize, RecievedBytesThreshold, Encoding, and NewLine settings. I am not at all familiar with these properties and I didn't find MSDN to be to helpful on explaining them either.

If you have any ideas or suggestions as to why I am getting incomplete lines of data in my upload, it would be most appreciated. Thank you for your assistance.

Upvotes: 2

Views: 212

Answers (2)

Icemanind
Icemanind

Reputation: 48726

The problem is in your encoding. Try changing the Encoding property to UTF8. The default is ASCII. In ASCII encoding, any character greater than 0x7F gets converted into a ? by default because ASCII only goes up to 0x7F (127 decimal).

Though that might fix your problem, the better way to go would be to read the data into a byte array, then use one of these encoding classes to convert it into a proper string. The reason why that works is because you no longer converting the received bytes into a string. You're using the Read(byte[], int, int) overload which doesn't do a string conversion. Its pure bytes.

Upvotes: 1

Janman
Janman

Reputation: 698

I think the problem lies in:

while ((bufferedData = comport.ReadLine()) != null)

Try changing the statement to something like:

    while(comport.BytesToRead>0)
{
uploadedData += comport.ReadExisting() + Environment.NewLine;
}

Let me know if that helped.

Upvotes: 1

Related Questions