Filestream creates or adds a problem

I am having problems with FileStreams. I'm in the process of writing a C # serial interface for an FPGA project I'm working on, receives a packet (containing 16 bytes), creates and writes the bytes to a file, and then appends to the generated file.

The program doesn't throw any errors, but it doesn't seem to have time to create the file and doesn't write any data.

Any ideas? Is there a better way to OpenOrAppend the file?

Thanks, Advance, Michael

    private void SendReceivedDataToFile(int sendBytes)
    {
        if (saveFileCreated == false)
        {
            FileStream writeFileStream = new FileStream(tbSaveDirectory.Text, FileMode.Create);
            writeFileStream.Write(oldData, 0, sendBytes);
            writeFileStream.Flush();
            writeFileStream.Close();
            saveFileCreated = true;
            readByteCount = readByteCount + sendBytes;
        }
        else
        {
            using (var writeFilestream2 = new FileStream(tbSaveDirectory.Text, FileMode.Append))
            {
                writeFilestream2.Write(oldData, 0, sendBytes);
                writeFilestream2.Flush();
                writeFilestream2.Close();
                readByteCount = readByteCount + sendBytes;
            }
        }

        if (readByteCount == readFileSize)                     // all data has been recieved so close file.
        {
            saveFileCreated = false;
        }
    }

      

+3


source to share


1 answer


FileMode.Append

already means "create or add", so you really need a piece of else {}

yours if

. You also don't need to call Flush()

or Close()

- deleting the thread will do it for you. Not sure not to write data ... have you tried to trace your code?

So first I would minify your code to



private void SendReceivedDataToFile(int sendBytes)
{
    using (var fs = new FileStream(tbSaveDirectory.Text, FileMode.Append))
        fs.Write(oldData, 0, sendBytes);
    readByteCount += sendBytes;
}

      

then try to figure out what exactly is in oldData

.

+7


source







All Articles