Tuesday, March 2, 2010

FTP File to the Remote Server with ASP.NET

I came across issues where I wasnt able to ftp files on the remove FTP Server programatically. Following were some of the issues:

File was not created on the server
File was created but was not accessible
File was created but was not readable (encoded)

Here's the code that takes care of that:


FtpWebRequest ftpFile;
//Access the file which has to be uploaded
FileInfo fileInf = new FileInfo(Server.MapPath("~/filename.txt"));

ftpFile = (FtpWebRequest)WebRequest.Create("ftp://ftp.servername.com/" + fileInf.Name);
ftpFile.Credentials = new NetworkCredential("username", "password");
//By default the connection is kept alive. Close the connection after the upload is done
ftpFile.KeepAlive = false;
ftpFile.Method = WebRequestMethods.Ftp.UploadFile;

//By default, Binary is true. If its true, the txt file becomes unreadable
ftpFile.UseBinary = false;
ftpFile.ContentLength = fileInf.Length;

Byte[] buff = new Byte[fileInf.Length];
int contentLen;
FileStream fs = fileInf.OpenRead();
Stream strm = ftpFile.GetRequestStream();
contentLen = fs.Read(buff, 0, buff.Length);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buff.Length);
}

strm.Close();
fs.Close();
ftpFile = null;

No comments: