public async Task <IActionResult> Edit(int id, IFormFile ImageFile, String oldName, [Bind("Id,Title,CreateDate,ImagePath,Description,CreatedDate,ModifiedDate")] News news) { Console.WriteLine("Idis:" + id); if (id != news.Id) { return(NotFound()); } //var oldNews = await _context.News.FindAsync(id); var subOldName = oldName.Substring(oldName.IndexOf('_') + 1); Console.WriteLine("Test old ImageName:" + oldName + " subOld Name:" + subOldName); if (ImageFile != null) { Console.WriteLine("There is image upload"); //Delete the old one String upLoadFolder = Path.Combine(hostingEnviroment.WebRootPath); String oldFilePath = upLoadFolder + oldName; Console.WriteLine("oldFullPath:" + oldFilePath); if (System.IO.File.Exists(oldFilePath)) { try { System.IO.File.Delete(oldFilePath); } catch (Exception e) { Console.Write(e.Message); } } //==================Create new one======== var uniqueFileName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(ImageFile.FileName); string filePath = Path.Combine(upLoadFolder, "images", uniqueFileName); news.ImagePath = "/images/" + uniqueFileName; using (var stream = System.IO.File.Create(filePath)) { await ImageFile.CopyToAsync(stream); } } else { Console.WriteLine("NotChanged"); } if (ModelState.IsValid) { try { _context.Update(news); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!NewsExists(news.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(news)); }