ila

ila

  • NA
  • 19.1k
  • 0

Pblm in downloading directories and files from ftp server using c#

Feb 12 2010 4:04 AM
Hi Sam
     I could download files with contents as u said.. Now i have enhanced it to download directories and files by using following code..

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace trial
{
    public struct FileStruct
    {
        public bool IsDirectory;
        public string Name;
    }
    public class FileDownloader
    {
        static void Main(string[] args)
        {
            string ftpServer = "ftp://********.com";
            string userName = "*********.com";
            string password = "*****";
            string sourcePath = "/vnaqc/";
            string destionationLocation = @"D:\project\ss\";
            try
            {
                FileDownloader fDownloader = new FileDownloader();                            
                bool db = fDownloader.DownloadDirectory(ftpServer, userName, password, sourcePath, destionationLocation);
                if (db)
                {
                    Console.WriteLine("downloaded ok");
                }
                else
                    Console.WriteLine("error");                   
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public bool DownloadDirectory(string FTPAddress, string username, string password, string sourcePath, string destPath)
        {
            try
            {              
                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);                   
                String str = reader.ReadToEnd();
                FileDownloader fDownloader = new FileDownloader();
                List<FileStruct> collectionOfFiles = new List<FileStruct>();
                collectionOfFiles = getFileList(str);           
                foreach (FileStruct fileName in collectionOfFiles)
                {
                    if (fileName.IsDirectory == true)
                    {
                        String newDesPath = Path.Combine(destPath, fileName.Name);
                        String newSourcePath = Path.Combine(sourcePath, fileName.Name);
                        Directory.CreateDirectory(newDesPath);
                        if (false == DownloadDirectory(FTPAddress, username, password, sourcePath, destPath))
                        {
                            return false;
                        }
                    }
                    else
                    {
                         if (false == downloadFile(FTPAddress, fileName.Name, username, password, sourcePath, destPath))
                            return false;
                    }
                }               
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }
        public List<FileStruct> getFileList(string str)
        {           
            Console.WriteLine("getting filelist");
            List<FileStruct> arrFiles = new List<FileStruct>();
            try
            {
                char[] separator ={ '\r', '\n' };
                string[] arrList = str.Split(separator,StringSplitOptions.RemoveEmptyEntries);               
                List<FileStruct> arrFiles1=new List<FileStruct>();               
                for (int i = 0; i < arrList.Length; i++)
                {
                    Console.WriteLine("For statement");
                    FileStruct objFile = new FileStruct();
                    String strRecord = arrList[i].Trim();
                    String strName = strRecord.Substring(39);
                    objFile.Name = strName;
                    if (strRecord.Substring(24, 5) == "")
                    {
                        objFile.IsDirectory = true;
                    }
                    else
                        objFile.IsDirectory = false;
                    arrFiles1[i] = objFile;                   
                }    
                return arrFiles1;
            }
            catch (Exception ex)
            {
                Console.WriteLine("catch statement");
                Console.WriteLine(ex.Message);
                return arrFiles;
            }           
        }
        public byte[] Download(string path)
        {

            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential("*******.com", "*****");
            return request.DownloadData(path);
        }
        public bool downloadFile(string FTPAddress, string filename, string username, string password, string sourcePath, string destPath)
        {
            Console.WriteLine("Downloading files");
            try
            {
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                request.UsePassive = true;
                request.UseBinary = false;
                request.KeepAlive = false;
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                byte[] Data = Download(FTPAddress + "/" + sourcePath + "/" + filename);
                DateTime mod = response.LastModified;
                DateTime obj = DateTime.Today;
                int res = DateTime.Compare(obj, mod);
                if (res == -1)
                {
                    FileStream fs = new FileStream(destPath, FileMode.Create);
                    fs.Write(Data, 0, Data.Length);
                    fs.Close();
                }
                else
                    Console.WriteLine("File not found");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
            Console.WriteLine("downloaded");
            return true;
        }

    }
}


But im getting exception like as follows:

startIndex cannot be larger than length of string.
Parameter name: startIndex



Answers (3)