Upload file in Dotnet

 Hello guys…

Here in this discussion we will see how to upload file in Dot-net.

firstly we have to create a private task async function as below.

 private async Task<string> WriteFile(IFormFile file)
{
//code
}

after that we simply get file name and

place the file in declared path and returns file name as below.


private async Task<string> WriteFile(IFormFile file)
    {
      string filename = "";
      try
      {
        var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
        filename = DateTime.Now.Ticks.ToString() + extension;

        var filepath = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\Files");

        if (!Directory.Exists(filepath))
        {
          Directory.CreateDirectory(filepath);
        }

        var exactpath = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\Files", filename);
        using (var stream = new FileStream(exactpath, FileMode.Create))
        {
          await file.CopyToAsync(stream);
        }
      }
      catch (Exception ex)
      {
      }
      return filename;
    }

Thank you.

Sign In or Register to comment.