Upload Files to FTP Server In asp .NET Core
File switch is a not unusual requirement for plenty of applications in these days’s digital international. One of the easiest ways to transfer files is through File Transfer Protocol (FTP). In this blog publish, we can walk you through the procedure of uploading a file to an FTP server using C#.
Below is the method for uploading a file to an FTP server using C#, including handling the connection, authentication, file data conversion, and response management.
private bool UploadFileToFtpLocation(string fileName, IFormFile file)
{
try
{
var ftpServerUrl = @"ftp://File Path/";
var username = @"iti";
var password = "iti@111";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpServerUrl + fileName));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.KeepAlive = false;
request.EnableSsl = false;
byte[] fileContents;
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
fileContents = memoryStream.ToArray();
}
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileContents, 0, fileContents.Length);
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
if (response.StatusCode == FtpStatusCode.ClosingData)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception ex)
{
throw new Exception("Error =>", ex);
}
}
This method takes two parameters,the name of the file to be uploaded (fileName) and the file itself (file), which is of type IFormFile.
I hope you found this tutorial easy to follow and understand.