ArgumentException:从 FileStream 复制到 MemoryStream 时参数无效

ArgumentException: Parameter is not valid while copying from FileStream to MemoryStream

我正在尝试使用 Memorystream 中的位图调整图像大小并保存到目录。它适用于第一个 运行,但如果我第二次尝试更新图像,我会收到 ArgumentException。

      public IActionResult UpdatePhoto(int id, IFormFile file)
         {
            var company = _context.Companies.FirstOrDefault(x => x.Id == id);
            var image = company.Logo;
            var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", image);
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }
             ResizeImage(file, file.FileName);
            company.Logo = file.FileName;
            _context.Companies.Update(company);
            _context.SaveChanges();
            return RedirectToAction(nameof(Index));
        }

我在调整大小方法中遇到错误

   public void ResizeImage(IFormFile  file, string FileName)
     { 
        using (var memoryStream = new MemoryStream())
         {
          file.CopyToAsync(memoryStream);
          Bitmap original = (Bitmap)Image.FromStream(memoryStream); 
          Bitmap processed = new Bitmap(original,new Size(300,300));
          var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", FileName  );
          processed.Save(path);
      }

您不应该在 awaitable 之外的方法中使用任何 async 方法。将您的代码更新为以下应该可以解决问题。

public void ResizeImage(IFormFile  file, string FileName)
{ 
using (var memoryStream = new MemoryStream())
    {
        file.CopyTo(memoryStream);
        Bitmap original = (Bitmap)Image.FromStream(memoryStream); 
        Bitmap processed = new Bitmap(original,new Size(300,300));
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/companies", FileName  );
        processed.Save(path);
    }
}