Exemplo n.º 1
0
        public async Task <IActionResult> EditAsync(CountryEditVM model)
        {
            if (ModelState.IsValid)
            {
                var country = _countryRepos.GetAll().FirstOrDefault(c => c.Name == model.Name);
                if (country == null)
                {
                    var serverPath = _env.ContentRootPath;   //Directory.GetCurrentDirectory(); //_env.WebRootPath;
                    var folerName  = @"\wwwroot\Uploads\";
                    var path       = serverPath + folerName; //

                    System.IO.File.Delete(Path.Combine(path, _countryRepos.GetById(model.Id).Flag));

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string ext      = Path.GetExtension(model.Flag.FileName);
                    string fileName = Path.GetRandomFileName() + ext;

                    string filePathSave = Path.Combine(path, fileName);

                    // сохраняем файл в папку Files в каталоге wwwroot
                    using (var fileStream = new FileStream(filePathSave, FileMode.Create))
                    {
                        await model.Flag.CopyToAsync(fileStream);
                    }

                    _countryRepos.Update(
                        new Country
                    {
                        Id         = model.Id,
                        Name       = model.Name,
                        Flag       = fileName,
                        DateModify = DateTime.Now
                    });
                }

                return(RedirectToAction("Index"));
            }
            ModelState.AddModelError("", "Дані вказано не коректно");
            return(View(model));
        }