Missing bytes sended through serial from C# app I am trying to store values sended by C# app in EEPROM via Arduino UNO. Here is a C# code that reads bytes from file (I'm 100% sure that there are, and always will be 256 bytes) and sends the buffer via SerialPort

        SerialPort port = new SerialPort("COM3", 9600);
        const string fileName = @"filepath";
        port.Open();
        byte[] buffer = File.ReadAllBytes(fileName);
        port.Write("W");
        port.Write(buffer, 0, buffer.Length);


Here is Arduino Code

int flag;
int datasize = 256;
byte byteBuffer[256];

void setup() {
  Serial.begin(9600);

  //read_write();
}


void loop() {
  readEEPROM();
  writeEEPROM();
  delay(500);
}

void readEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag == 'R') {
      for (int i = 0; i &lt; datasize; i++) {
        byteBuffer[i] = ME.read(i);
      }
      flag = 'S';
      Serial.write(byteBuffer, datasize);
    }
  }
}
void writeEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag = 'W') {
      int bytesRead = 0;
      digitalWrite(LED_BUILTIN, HIGH);
      delay(500);
      while (bytesRead &lt; 256) {
        if (Serial.available() &gt; 0) {
          byteBuffer[bytesRead] = Serial.read();
          bytesRead++;
        }
      }
  digitalWrite(LED_BUILTIN, LOW);

  for (int i = 0; i &lt; datasize; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    ME.writeEnable();
    ME.write(i, byteBuffer[i]);
    ME.writeDisable();
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
  flag = 'S';
   }
  }
 }


As you can see in writeEEPROM function arduino turns on BUILTIN_LED before it starts reading serial, sadly the LED is never turning off, which makes me think like there are never 256 bytes in SerialPort, whats more, when i turn the c# program on again, the arduino successfully leaves the while loop, but the data is deformed, I mean the values are different.
There's two basic things wrong here.

First is your way of opening the serial port and immediately sending data.  The Arduino is reset when you open the serial port and the bootloader runs. This takes a second or so, and during that time any data that you send is lost.

Secondly you're not checking for a flag of "W" but instead you're assigning "W" to the flag, which always succeeds.

The line

if (flag = 'W') {


should read

if (flag == 'W') {


To get around the first problem you can either just put a delay (however you do that in C#) after opening the port and before sending the "W", or you could implement a "Are you there?" handshake to look for the Arduino.

One example would be to add an extra flag of (say) "?" to which the Arduino simply responds "Y".

The PC then sends "?" and, if it doesn't receive "Y" within a certain timeout it loops sending "?" again.

Once it receives "Y" then it knows the Arduino is there and ready to receive data, so you can send the "W" command and the data.