简体   繁体   中英

Filestream create or append issue

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

The program is not throwing any errors but doesn't appear to get past creating the file and does not write any data to it.

Any Ideas? IS there a better way to OpenOrAppend a file?

Thanks in 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;
        }
    }

FileMode.Append already means "create or append", so really you only need the else {} part of your if . You also don't need to call Flush() or Close() - disposing the stream will do that for you. Not sure about not writing data... did you try to trace your code?

So first I would reduce 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 what exactly in the oldData .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM