In almost all ASP.NET web application, we have to write
a code to upload file to FTP servers with SSL for security reasons.
Here is simple and full code to upload file via FTP
with SSL.
It uses FtpWebRequest
for creating FTP connection to server by proving FTP URL, SSL ceritifcates with
necessary credentials. Below code reads the file byte by byte and upload the
final stream to FTP server.
RemoteCertificateValidationCallback orgCallback = ServicePointManager.ServerCertificateValidationCallback;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(OnValidateCertificate);
ServicePointManager.Expect100Continue = true;
Stream requestStream = null;
FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create("FTP URL
ADDRESS");
ftpRequest.Method
= WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy
= null;
ftpRequest.UseBinary
= true;
ftpRequest.KeepAlive
= false;
ftpRequest.EnableSsl
= isSSL;
ftpRequest.UsePassive
= isUsePassive;
ftpRequest.Credentials
= new NetworkCredential(userName,
password);
ftpRequest.UsePassive
= isUsePassive;
using (requestStream = ftpRequest.GetRequestStream())
{
const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
int count = 0;
int readBytes = 0;
FileInfo objfileInfo = new FileInfo(completeFilePath);
FileStream stream = objfileInfo.OpenRead();
do
{
readBytes = stream.Read(buffer, 0,
bufferLength);
requestStream.Write(buffer, 0,
readBytes);
count += readBytes;
}
while (readBytes != 0);
}
public static bool OnValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return false;
}
Please leave your comments or share this code if it’s
useful for you.
No comments:
Post a Comment