DirectoryNotFoundException While Trying To Uplode Any File In EF core Razor Pages

Arnab 66 Reputation points
2022-08-24T12:00:43.343+00:00

I am Trying To make A form In Ef core Razor pages where I have to upload Salary slip and save it in DB. My Entity Class Is
public class SalarySlip
{
public int Id { get; set; }

        //Later It will be a dropdown List Of Employee Type.  
        public string EmpName { get; set; }  
        public string SlipName  { get; set; }  
        public byte[] Content { get; set; }  
    }  

my Create Model

 public class CreateModel : PageModel  
    {  
        private readonly ApplicationDbContext _db;  
        private readonly IWebHostEnvironment _hostEnvironment;  
  
        [BindProperty]  
        public SalarySlip SalarySlip  { get; set; }  
  
        public CreateModel(ApplicationDbContext db , IWebHostEnvironment webHostEnvironment)  
        {  
            _db = db;  
            _hostEnvironment = webHostEnvironment;  
        }  
        [BindProperty]  
        public InputModel FileUpload { get; set; }  
  
        public class InputModel  
        {  
            public IFormFile FormFile { get; set; }  
        }  
        public IActionResult OnGet()  
        {  
            return Page();  
        }  
        public async Task<IActionResult> OnPostAsync()  
        {  
            if (!ModelState.IsValid)  
            {  
                return Page();  
            }  
            // Uplode file to folder.  
            if (FileUpload.FormFile.Length > 0)  
            {  
                using (var stream = new FileStream(Path.Combine(_hostEnvironment.WebRootPath, "uploadfiles", FileUpload.FormFile.FileName), FileMode.Create))  
                {  
                    await FileUpload.FormFile.CopyToAsync(stream);  
                }  
            }  
            //save image to dataBase.  
            using(var memoryStream = new MemoryStream())  
            {  
                await FileUpload.FormFile.CopyToAsync(memoryStream);  
                //uplode the file if Less than 2 MB.  
                if (memoryStream.Length < 2097152)  
                {  
                    var file = new SalarySlip()  
                    {  
                        SlipName = FileUpload.FormFile.FileName,  
                        Content = memoryStream.ToArray()  
                    };  
                    _db.SalarySlip.Add(file);  
                    await _db.SaveChangesAsync();  
                }  
                else  
                {  
                    ModelState.AddModelError("SalarySlip", "The File is Too Large.");  
                }  
            }  
            //_db.SalarySlip.Add(SalarySlip);  
            //await _db.SaveChangesAsync();  
  
            return RedirectToPage("Index");  
        }  
    }  

My cshtml.cs Razor page is

@page  
@model New11.Pages.SalarySlips.CreateModel  
@{  
  
    ViewData["Title"] = "Create";  
}  
<br />  
<h2 class="text-info">Create Biometric </h2>  
<br />  
<form method="post" enctype="multipart/form-data">  
    <div class="border backgroundWhite">  
        <div class="form-group row">  
            <div class="col-2">  
                <label asp-for="SalarySlip.EmpName"></label>  
            </div>  
            <div class="col-5">  
                <input asp-for="SalarySlip.EmpName" class="form-control" />  
            </div>  
            @*<span asp-validation-for="BiometricAsset.Name" class="text-danger"></span>*@  
        </div>  
        <div class="form-group row">  
            <div class="col-2">  
                <label asp-for="SalarySlip.SlipName"></label>  
            </div>  
            <div class="col-5">  
                <input asp-for="SalarySlip.SlipName" class="form-control" />  
            </div>  
            @*<span asp-validation-for="BiometricAsset.Name" class="text-danger"></span>*@  
        </div>  
        <div class="form-group ">  
            <lebel asp-for="FileUplode.FormFile" class="custom-control-label"></lebel>  
            <input asp-for="FileUpload.FormFile" class="form-control" type="file" />  
            <span asp-validation-for="FileUpload.FormFile" class="text-danger"></span>  
  
        </div>  
  
    </div>  
     
        <div class="form-group row">  
            <div class="col-5 offset-2">  
                <partial name="_CreateAndBackToListButton" />  
            </div>  
        </div>  
      
</form>  
  
@section Scripts{  
    @{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }  
}  

But After Execution I am Getting This Exception
234496-screenshot-2022-08-24-142513.jpg

So Plzz suggest What I am Doing Wrong Here?
I already Took Reference From here

https://learn.microsoft.com/en-us/answers/questions/807026/upload-image-to-aspnet-razor-page.html#answer-979687

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,189 questions
0 comments No comments
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,016 Reputation points Microsoft Vendor
    2022-08-25T01:45:13.817+00:00

    Hi @Arnab ,

    234704-image.png

    The issue should be relates that the wwwroot folder doesn't contain the uploadfiles folder. So when upload the file to folder, it will show the directory not found exception.

    To solve this issue, you can right click the wwwroot folder and add a uploadfiles folder. Or use the following code to check whether the folder exist or not, and then create the folder.

            var folderpath = Path.Combine(_hostenvironment.WebRootPath, "uploadfiles");  
            // Determine whether the directory exists.  
            if (!Directory.Exists(folderpath))  
            {  
                // Try to create the directory.  
                DirectoryInfo di = Directory.CreateDirectory(folderpath);  
            }  
               
            //upload file to folder  
            if (FileUpload.FormFile.Length > 0)  
            {   
                using (var stream = new FileStream(Path.Combine(_hostenvironment.WebRootPath, "uploadfiles", FileUpload.FormFile.FileName), FileMode.Create))  
                {  
                    await FileUpload.FormFile.CopyToAsync(stream);   
                }   
            }  
    

    The folder structure as below:

    234677-image.png


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Arnab 66 Reputation points
    2022-08-30T11:07:05.717+00:00

    @Zhi Lv - MSFT Thanks .I have one more questions regarding this .How to Download The uploaded files from Data Base and save it to local folder.
    ?

    0 comments No comments