FTP Upload file
April 21, 2009
Don't know what to read next? Check out the list of popular posts. People like them, they should be good.
A code snippet upload file using FTP. With some tweak, we could also get the percentage out of this.
void FTPUpload(string filename, string username, string password, string UploadTo)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(UploadTo + fileInf.Name));
// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(username, password);
//Disconnect when finish
reqFTP.KeepAlive = false;
// Request upload file.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// Using Binary so we could upload whatever we want
reqFTP.UseBinary = true;
// Send the size of fize
reqFTP.ContentLength = fileInf.Length;
// The buffer size is set to 2kb
int buffLength = 2048;
//Arry to store read file
byte[] buff = new byte[buffLength];
int contentLen;
// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
FileStream fs = fileInf.OpenRead();
try
{
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();
// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);
// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Upload Error");
}
}
Leave a Reply