Wednesday, July 2, 2008

FTP Upload in C# .NET

This is my first time to post a code. Well, I'm just so happy that if finally worked after a series of errors. So I want to share this code taken from a reference (ASP Alliance). We can find a lot of similar codes but I chose this reference because this was my starting point (recommended by my Project Manager).

private string ftpUsername; //username
private string ftpPassword; //password

private void UploadImage(string filename)
{
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + ftpAddress + "/" + fileInf.Name;
FtpWebRequest reqFTP;

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpAddress + "/" + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
reqFTP.Timeout = 1000000000; //set to very high value
reqFTP.KeepAlive = false;
reqFTP.ReadWriteTimeout = 1000000000; //set to very high value
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = false; //my own addition
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048; //set to 2kb
byte[] buff = new byte[buffLength];
int contentLen;

FileStream fs = fileInf.OpenRead();

try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception ex) {
throw new ApplicationException(ex.Message);
}
}
So there it is. I added some modifications like reqFTP.UsePassive = false; since I kept getting a "227" error. Found a forum that answers the same error, and suggested to include the said code. And after that, all worked perfectly. Kudos!

1 comment:

Anonymous said...

oh this is good :)