简体   繁体   English

将MemoryStream转换为FileStream时FileStream数据不完整

[英]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. 使用MemoryStream创建StreamWriter并对其进行写入的方法似乎可以正常工作-“ while(rdr.Read())”循环执行约40次。 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. 但是,当我使用将MemoryStream转换为FileStream的方法时,生成的制表符分隔的文件仅显示34行,而第34行甚至不完整。 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): 在将数据写入MemoryStream的方法中,您需要在开始将其转换为FileStream的方法之前将其添加到最后(其中streamWriter是写入到MemoryStream的StreamWriter):

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: 如果使用的是.Net 4.0+,则可以使用新的Stream.CopyTo接口:

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

The data will be flushed when output is disposed. 处理output时,将刷新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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