我不明白我在这里做错了什么。我生成了几个内存流,在 Debug模式下我看到它们已被填充。但是,当我尝试将 MemoryStream
复制到 FileStream
以保存文件时,fileStream
未填充且文件长度为 0 字节(空)。
这是我的代码
if (file.ContentLength > 0)
{
var bytes = ImageUploader.FilestreamToBytes(file); // bytes is populated
using (var inStream = new MemoryStream(bytes)) // inStream is populated
{
using (var outStream = new MemoryStream())
{
using (var imageFactory = new ImageFactory())
{
imageFactory.Load(inStream)
.Resize(new Size(320, 0))
.Format(ImageFormat.Jpeg)
.Quality(70)
.Save(outStream);
}
// outStream is populated here
var fileName = "test.jpg";
using (var fileStream = new FileStream(Server.MapPath("~/content/u/") + fileName, FileMode.CreateNew, FileAccess.ReadWrite))
{
outStream.CopyTo(fileStream); // fileStream is not populated
}
}
}
}
最佳答案
复制前需要重新设置流的位置。
outStream.Position = 0;
outStream.CopyTo(fileStream);
您在使用 imageFactory
保存文件时使用了 outStream
。该函数填充了 outStream
。在填充 outStream
时,位置设置为填充区域的末尾。这样一来,当您继续向 Steam 写入字节时,它不会覆盖现有字节。但是要阅读它(出于复制目的),您需要将位置设置为开始,以便您可以从头开始阅读。
关于c# - 将 MemoryStream 复制到 FileStream 并保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18766055/