Search code examples
c#filestream

filestream c# read data repeatedly


am using filestream with file handle to communicate with USB HID Device the Device Resend The Report (array of byte[64]) As It's Received. receive method occurs in another thread that fires an event when reports is read ,,

Every attempt sends ONLY ONE "Report" first attempt is Ok ,, 1 Report received but when i send again it reads it twice ! (is it available twice in the filestream ??) on the next attempt the event fires twice again ! after that it add it three times for the next 3 attempts

attempt 1  1 report received
attempt 2  2 reports received
attempt 3  2 reports received
attempt 3  3 reports received
attempt 4  3 reports received
attempt 5  3 reports received
attempt 6  4 reports received
attempt 7  4 reports received

any more reports sent cause 4 reports received is there ANY logical description for this ?

code:

private void WriteData(object Data)
    {
        byte[] data = Data as byte[];
        int bytesSent = 0;
        while (bytesSent < data.Length)
        {
            byte [] OutputReportBuffer = new byte[64];
            for (int i = 0; i < OutputReportBuffer.Length; i++)
                if (bytesSent < data.Length)
                {
                    OutputReportBuffer[i] = data[bytesSent];
                    bytesSent++;
                }
                else OutputReportBuffer[i] = 0;
            try
            {
                fileStream.Write(OutputReportBuffer, 0, OutputReportBuffer.Length);
                fileStream.Flush();
            }
            catch///deducted code
        }
    }

here where its received (separate thread that fires event when data is read)

private void ReadData()
    {
        while (true)
        {
            try
            {
                if (fileStream.Read(ReceivedDataBuffer, 0, ReceivedDataBuffer.Length) > 0)
                {
                    _Context.Send(o =>
                    {
                        if (DataReceived != null)
                            DataReceived(this, new DataReceivedEventArgs(ReceivedDataBuffer));
                    }, null);
                }
            }
            catch //deducted code
        }
}

Solution

  • You are not using the return value of Read to find out how many bytes you actually got.