Thursday, May 26, 2011

How to do FTP in C#

FtpWebResponse ftpResponse = null;

FtpWebRequest ftpRequest = null;

ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + m_Server + "/" + Path.GetFileName(sFileNameWithLocation) + "");
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
ftpRequest.Proxy = null;
ftpRequest.UseBinary = true;
ftpRequest.Credentials = new NetworkCredential(sUserName, sPassword);

FileInfo fi = new FileInfo(sFileNameWithLocation);
byte[] fileContents = new byte[fi.Length];

using (FileStream fs = fi.OpenRead())
{
    fs.Read(fileContents, 0, Convert.ToInt32(fi.Length));
}

using (Stream writer = ftpRequest.GetRequestStream())
{
    writer.Write(fileContents, 0, fileContents.Length);
}

ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
Response.Write(ftpResponse.StatusDescription);

No comments:

Post a Comment