Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, March 13, 2014

How to upload file via FTP in ASP.NET using C#

In almost all ASP.NET web application, we have to write a code to upload file to FTP servers.

Here is simple and full code to upload file via FTP.

It uses FtpWebRequest for creating FTP connection to server by proving FTP URL with necessary credentials. Code read the file byte by byte and upload the final stream to FTP server.

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.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();
        readBytes = stream.Read(buffer, 0, bufferLength);
        requestStream.Write(buffer, 0, readBytes);
        count += readBytes;
    while (readBytes != 0);

Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment