简体   繁体   English

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

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

I am trying to resize image using bitmap from Memorystream and save to directory.我正在尝试使用来自 Memorystream 的 bitmap 调整图像大小并保存到目录。 It works on the first run but if i try to update the image second time i am getting ArgumentException.它在第一次运行时有效,但如果我第二次尝试更新图像,我会收到 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));
        }

I am getting error in Resize Method我在调整大小方法中遇到错误

   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);
      }

you shouldn't be using any of the async methods inside the methods which are not awaitable .您不应该在不可awaitable的方法中使用任何async方法。 updating your code to following should fix the issue.将您的代码更新为以下应该可以解决问题。

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);
    }
}

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

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