简体   繁体   中英

FileStream Data Incomplete when Converting MemoryStream to FileStream

I'm trying to create a tab-delimited file using data retrieved from the database. The method for using a MemoryStream to create a StreamWriter and write to it seems to work fine - the "while(rdr.Read())" loop executes about 40 times. But when I get to the method for converting the MemoryStream to a FileStream, the resulting tab-delimted file only shows 34 lines, and the 34th line isn't even complete. Something is limiting the output. Don't see anything wrong with the data itself that would cause it to suddenly terminate, either.

Here's the conversion method:

protected internal static void ConvertMemoryStreamToFileStream(MemoryStream ms, String newFilePath){
        using (FileStream fs = File.OpenWrite(newFilePath)){
            const int blockSize = 1024;
            var buffer = new byte[blockSize];
            int numBytes;
            ms.Seek(0, SeekOrigin.Begin);
            while ((numBytes = ms.Read(buffer, 0, blockSize)) > 0){
                fs.Write(buffer, 0, numBytes);
            }
        }
    }

Any and all help is appreciated, thank you.

Found the solution myself, since no one would help. :(

In the method for writing the data to the MemoryStream, you need to add this to the very end before starting the method for turning it into a FileStream (where streamWriter is the StreamWriter writing to the MemoryStream):

streamWriter.Flush();

Apparently this adds all "buffered" data to the stream, whatever that means. Working with memory sucks.

If this is using .Net 4.0+ you can use the new Stream.CopyTo interface:

ms.Seek(0, SeekOrigin.Begin);
using (var output = File.OpenWrite(newFilePath))
{
    ms.CopyTo(output);
}

The data will be flushed when output is disposed.

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