MemoryStream转FileStream时FileStream数据不完整
我正在尝试使用从数据库检索的数据创建制表符分隔的文件。使用 MemoryStream 创建 StreamWriter 并向其写入的方法似乎工作正常 - “while(rdr.Read())”循环执行大约 40 次。但是,当我了解将 MemoryStream 转换为 FileStream 的方法时,生成的制表符分隔文件仅显示 34 行,并且第 34 行甚至不完整。有些东西限制了输出。也不认为数据本身有任何问题会导致其突然终止。
这是转换方法:
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);
}
}
}
感谢您的任何帮助,谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我自己找到了解决方案,因为没有人会帮忙。 :(
在将数据写入MemoryStream的方法中,您需要在开始将其转换为FileStream的方法之前将其添加到最后(其中streamWriter是写入MemoryStream的StreamWriter):
显然这会添加所有“缓冲” “将数据传输到流中,无论这意味着什么。使用内存很糟糕。
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):
Apparently this adds all "buffered" data to the stream, whatever that means. Working with memory sucks.
如果使用 .Net 4.0+,您可以使用新的
Stream.CopyTo
接口:当
output
被释放时,数据将被刷新。If this is using .Net 4.0+ you can use the new
Stream.CopyTo
interface:The data will be flushed when
output
is disposed.