简体   繁体   中英

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. It works on the first run but if i try to update the image second time i am getting 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 . 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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