public async Task <IActionResult> Cabinet(Product model, IFormFile upload) { if ((ModelState.IsValid) && (upload != null)) { var filePath = _app.WebRootPath + "\\img\\"; DirectoryInfo dirInfo = new DirectoryInfo(filePath); var permissionSet = new PermissionSet(PermissionState.None); var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filePath); permissionSet.AddPermission(writePermission); FileInfo sameFile = new FileInfo(filePath + upload.FileName); if (!sameFile.Exists) { using (FileStream stream = new FileStream(filePath + "\\" + upload.FileName, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite)) { await upload.CopyToAsync(stream); } model.DoorId = upload.FileName; _context.Products.Add(model); _context.SaveChanges(); ViewBag.UserMessage = "Товар добавлен."; } else { int number = 1; bool noOut = true; var fileNameCut = upload.FileName.Remove(upload.FileName.IndexOf('.'), upload.FileName.Length - upload.FileName.IndexOf('.')); do { FileInfo newFile1 = new FileInfo(filePath + fileNameCut + number.ToString() + ".jpg"); number++; noOut = newFile1.Exists; } while (noOut); fileNameCut += number.ToString() + ".jpg"; using (FileStream stream = new FileStream(filePath + "\\" + fileNameCut, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite)) { await upload.CopyToAsync(stream); } model.DoorId = fileNameCut; _context.Products.Add(model); _context.SaveChanges(); ViewBag.UserMessage = "Товар добавлен."; } //ViewBag.UserMessage = "A file with this name already exists"; ModelState.Clear(); } return(View()); }
public void SaveChanges() { context.SaveChanges(); }