c# - MemoryStream 抛出 InvalidOperationException 类型的异常
问题描述
我希望你能帮助:)
在我的MVC.net core 2.2中,调试的时候很简单:
MemoryStream ms = new MemoryStream();
初始化后,它给了我一个:
ReadTimeout: 'ms.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout: 'ms.WriteTimeout' threw an exception of type 'System.InvalidOperationException'
现在解决方案不会崩溃或任何事情。但是,如果我检查 Visual Studio 中的“ms”,那就是它所说的。
我想做的是通过 SixLabors.ImageSharp 做:
IFormFile file = viewModel.File.Image;
using (Image<Rgba32> image = Image.Load(file.OpenReadStream()))
using (var ms = new MemoryStream())
{
image.Mutate(x => x.Resize(1000, 1000));
SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder jpegEncoder =
new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder();
jpegEncoder.Quality = 80;
image.Save(ms, jpegEncoder);
StorageCredentials storageCredentials = new StorageCredentials("Name", "KeyValue");
// Create cloudstorage account by passing the storagecredentials
CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
CloudBlobContainer container = blobClient.GetContainerReference("storagefolder");
// Get the reference to the block blob from the container
CloudBlockBlob blockBlob = container.GetBlockBlobReference("image.jpg");
await blockBlob.UploadFromStreamAsync(ms);
}
但是保存的流是空的(调试时Capacity,Length和Position中有值。但是将其上传到azure blob存储后,大小为0)。
亲切的问候安达·亨德里克森
解决方案
对内存流的写操作不是原子的,它们被缓冲以提高效率。您需要先刷新流。
第二个问题是,您开始将内存流复制到输出流,从流的末尾开始。因此,将内存流重新定位到开头。
因此,在将流写入输出之前:
ms.Flush();
ms.Position = 0; // or ms.Seek(0, SeekOrigin.Begin);
然后打电话
await blockBlob.UploadFromStreamAsync(ms);
推荐阅读
- c# - RS232 串行端口嗅探器字节乱序
- vb.net - 如何将 DataGridView 中的数据导出到 VB.NET 中的文本文件
- html - css中略微弯曲的底部div
- python - 将 Pandas 频率更改为非时间元素
- telegram - 固定消息可以有内联按钮吗?
- c++ - boost:如何在给定 ptime 之前休眠当前线程?
- c# - 使用 payu-custom-browser Xamarin Android 绑定库时出现运行时错误说 CBActivity:您需要使用 Theme.AppCompat 主题
- javascript - 如何在 Eclipse 控制台中对终止事件(红色按钮)执行操作?
- entity-framework-core - Ef core Ownsone 问题“正在共享餐桌”
- email - Microsoft Office 365 范围活动 - Office365message 获取邮件主题