Monday, October 19, 2009

FTP oprations in C#, GET and PUT oprations, Checking FTP Directory Listing




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

///
/// Summary description for FTP
///
namespace Tools
{
    public class FTP
    {
        public FTP()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void downloadFiles(List<String> files, String targetFolder, string FTPAddress,string username, string password)
        {
            foreach (string fileToDownload in files)
            {
                downloadFile(FTPAddress, fileToDownload, targetFolder, username, password);
            }
        }
        public static void downloadFile(string FTPAddress, string filename,String targetFolder, string username, string password)
        {
            byte[] downloadedData = new byte[0];

            try
            {
               
                //Create FTP request
                //Note: format is ftp://server.com/file.ext
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;

                //Get the file size first (for progress bar)
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true; //don't close the connection

                int dataLength = (int)request.GetResponse().ContentLength;

                //Now get the actual data
                request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false; //close the connection when done

                //Streams
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream reader = response.GetResponseStream();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024]; //downloads in chuncks

                while (true)
                {
                   

                    //Try to read the data
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                                              
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();
               
                // Save File to Disk
                FileStream newFile = new FileStream(targetFolder + "\\" + filename, FileMode.Create);
                newFile.Write(downloadedData, 0, downloadedData.Length);
                newFile.Close();
               
                //Clean up
                reader.Close();
                memStream.Close();
                response.Close();

                //MessageBox.Show("Downloaded Successfully");
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server.");
            }

            //txtData.Text = downloadedData.Length.ToString();
            //this.Text = "Download Data through FTP";

            //username = string.Empty;
            //password = string.Empty;
        }

        public static List<String> getFileList(string FTPAddress, string username, string password)
        {
            List<string> files = new List<string>();

            try
            {

                //Create FTP request
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;


                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;



                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                while (!reader.EndOfStream)
                {
                    //Application.DoEvents();
                    files.Add(reader.ReadLine());
                }

                //Clean-up
                reader.Close();
                responseStream.Close(); //redundant
                response.Close();
                return files;
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server");
                files.RemoveRange(0, files.Count - 1);
                return files;
            }
        }
        public static bool uploadFile(string FTPAddress, string filePath, string username, string password)
        {
            try
            {
                string finePathName = Path.GetFileName(filePath);
                //Create FTP request
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath));

                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                //Load the file
                FileStream stream = File.OpenRead(filePath);
                byte[] buffer = new byte[stream.Length];

                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

    }
}



No comments:

Post a Comment

Followers

Search This Blog