File Upload Using FTP In .Net Core 6.0

In this article, we are going to learn about how to upload files using FTP in .Net Core 6.0.

In my recent project, I got the requirement where I have to upload files with the help of FTP but without using a static file path. So I found and implement some pieces of code to achieve this, let us understand with the help of the below example.

What is FTP?

FTP stands for File Transfer Protocol. It is a network protocol for transmitting files between computers over Transmission Control Protocol/Internet Protocol connections. It is considered an application layer protocol.

The FTP refers to a process that involves the transfer of files between devices over a network. this process works when one party allows another to send or receive files over the internet. Originally used for users to communicate and exchange information between two physical devices

Benefits of FTP

  • Huge file sizes can be transferred with ease.
  • Faster transfer speed than HTTP.
  • Using FTP data can be recovered.
  • Files uploading and downloading are faster.
  • Users can transfer files and directories.

Prerequisites

First, create FileUploadVM class in the Model folder.

public class FileUploadVM
{
   [Required]
   public IFormFile File { get; set; }
}

Open your controller and paste the below code into it.

[HttpPost]
[Route("FTPUpload")]
public async Task<IActionResult> FTPUpload([FromForm] FileUploadVM fileUploadVM)
{
    try
    {
        string uploadUrl = String.Format("ftp://{0}/{1}/{2}", "ftp.hafeezjaha.com", "data", fileUploadVM.File.FileName);
        var request = (FtpWebRequest)WebRequest.Create(uploadUrl);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Credentials = new NetworkCredential("username", "password");
        byte[] buffer = new byte[1024];
        var stream = fileUploadVM.File.OpenReadStream();
        byte[] fileContents;
        using (var ms = new MemoryStream())
        {
          int read;
          while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
          {
            ms.Write(buffer, 0, read);
          }
          fileContents = ms.ToArray();
        }
        using (Stream requestStream = request.GetRequestStream())
        {
           requestStream.Write(fileContents, 0, fileContents.Length);
        }
        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
        Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
        return Ok("Upload Successfuly.");
   }
   catch (Exception ex)
   {
      return BadRequest("Upload Failed: " + ex.Message);
   }
}

That’s it.

As you can see in the above image file is uploaded successfully.

Also check, Minimal API in .Net Core 6

3 Comments

  1. mohammad

    Hello
    I use the same codes in asp.netCore6

    But when the image or any type of file is sent to the download host, the following error is displayed UnauthorizedAccessException: Access to the path ‘C:\public_html\Images’ is denied.

    Important note: When the project is run on the local host and we are in the development environment, the upload is done without any problem. But when the site is running on the server, it can no longer communicate with the download host to upload files, and it is really surprising.

    We have checked the access to the folders in the download host and all access has been granted. But we face this error again: UnauthorizedAccessException: Access to the path ‘C:\public_html\Images’ is denied.

    For further investigation, I introduced a folder that does not exist in the download host in my code for uploading a file called test. It was interesting . When I ran the site on the local host, it gave an error that the path could not be found, but when I ran my site on the server, it gave this error again.

    UnauthorizedAccessException: Access to path ‘C:\public_html\test’ is denied.

    Even though the test folder doesn’t exist at all. So now we assume that the problem is not the download, but we don’t know where the problem is. please guide me. Thanks

    0
    0
    Reply
  2. Marek

    All work is done synchronously, what sounds bad when it comes to disk i/o operations.

    0
    0
    Reply
  3. Jbcastillo

    THats awesone but we need up the file with exten i try to do it but only up the file in raw format

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories