/ Published in: C#
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* * FileName: SimpleFTP.cs * Classes Included: SimpleFTP * Purpose: The SimpleFTP is a class that allows for the FTP transfer of remote * data to the local hard drive. It also provides three delegates to report * progress to the calling method. * Created on: 09 Dec 2008 * Created by: wraith808 * * History: * Date Who Note * --------------------------------------------------------------------------- * 12-09-2008 wraith808 Created * */ using System; using System.IO; using System.Net; namespace UtilsLib { public delegate void OnFTPFinish(bool ftpSuccessful, string message); public delegate void OnFTPStart(string message); public delegate void OnFTPProgress(int bytesTransferred, string message); public class SimpleFTP { private bool _UseBinaryMode = true; public bool UseBinaryMode { get { return _UseBinaryMode; } set { _UseBinaryMode = value; } } string _LocalFilePath; public string LocalFilePath { get { return _LocalFilePath; } set { _LocalFilePath = value; } } string _LocalFileName; public string LocalFileName { get { return _LocalFileName; } set { _LocalFileName = value; } } string _URI; public string URI { get { return _URI; } set { _URI = value; } } string _UserId; public string UserId { get { return _UserId; } set { _UserId = value; } } string _Password; public string Password { get { return _Password; } set { _Password = value; } } string _RemoteFileName; public string RemoteFileName { get { return _RemoteFileName; } set { _RemoteFileName = value; } } public bool InitiateTransfer(OnFTPProgress OnProgress, OnFTPStart OnStart, OnFTPFinish OnFinish) { bool transferResult = true; if ((_LocalFileName.Length == 0) || (_LocalFilePath.Length == 0) || (_UserId.Length == 0) || (_Password.Length == 0) || (_URI.Length == 0) || (_RemoteFileName.Length == 0)) { OnFinish(false, "All parameters not initialized. Transfer aborted."); transferResult = false; } else { var reqFTP = (FtpWebRequest)WebRequest.Create(_URI + "//'" + _RemoteFileName + "'"); try { reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = _UseBinaryMode; var response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; long transferLength = 0; OnStart(string.Format("Preparing to transfer {0} bytes", cl)); const int bufferSize = 2048; int readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); OnProgress(readCount, string.Format("Transferred {0} bytes.", readCount)); transferLength += readCount; readCount = ftpStream.Read(buffer, 0, bufferSize); } OnFinish(true, string.Format("{0} bytes transferred.", transferLength)); ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception e) { OnFinish(false, string.Format("Failed: {0}", e.Message)); transferResult = false; } } return transferResult; } } }