Friday, September 12, 2014

C# Downloading Multiple Files From FTP

Program.cs:
---------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
using System.Net.Mail;

namespace DownloadRMAfromDCL
{
    class Program
    {
        private static Boolean ftpAnnonymous = Convert.ToBoolean(ConfigurationManager.AppSettings["FTPanonymous?"]);
        private static string ftpUserName = ConfigurationManager.AppSettings["FTPuserName"];
        private static string ftpUserPassword = ConfigurationManager.AppSettings["FTPpassword"];
        private static string localDestination = ConfigurationManager.AppSettings["LocalDestination"];
        private static string localDestination2 = ConfigurationManager.AppSettings["LocalDestination2"];
        private static Boolean Flag = true;

        static void Main(string[] args)
        {
            CreateLogFile.MessageLog("Listing Files.....");
            string[] files = GetFileList();
            CreateLogFile.MessageLog("Files Listed.");
            if (files == null)
            {
                CreateLogFile.MessageLog("No Files To Download");
                return;
            }
            else
            {
                foreach (string file in files)
                {
                    CreateLogFile.MessageLog(file);
                    Download(file, localDestination);
                    //Download(file, localDestination2);
                    if (Flag)
                    {
                        CreateLogFile.MessageLog("file " + file + " downloaded successfully");
                        SendEmail(file);
                        CreateLogFile.MessageLog("Email Sent");
                        //DeleteFileOnServer(file);
                    }
                }
            }
        }

        private static string[] GetFileList()                         //gets files in the directory
        {
            string[] downloadFiles;
            StringBuilder result = new StringBuilder();
            string uri = ConfigurationManager.AppSettings["FTPDirectory"];

            WebResponse response = null;
            StreamReader reader = null;
            try
            {
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                CreateLogFile.MessageLog("FTPWebRequest");
                if (!ftpAnnonymous)
                {
                    reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpUserPassword);
                }
                reqFTP.UseBinary = true;
                //reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpUserPassword);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                reqFTP.UsePassive = true;
                CreateLogFile.MessageLog("Getting Response from server.");
                response = reqFTP.GetResponse();
                CreateLogFile.MessageLog("Got Response, Reading ...");
                reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                        result.Append(line);
                        result.Append("\n");
                                 line = reader.ReadLine();
                }

                // to remove the trailing '\n'
                if (result.ToString().Contains('\n'))
                {
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    return result.ToString().Split('\n');
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                CreateLogFile.MessageLog(ex.Message);
                downloadFiles = null;
                return downloadFiles;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }

        }

        private static void Download(string file, string destination)
        {
            try
            {
                string dest = destination;
                string uri = ConfigurationManager.AppSettings["FTPDirectory"] + file;
                Uri serverUri = new Uri(uri);
                if (serverUri.Scheme != Uri.UriSchemeFtp)
                {
                    return;
                }
                FtpWebRequest reqFTP;
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                if (!ftpAnnonymous)
                {
                    reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpUserPassword);
                }
                reqFTP.KeepAlive = false;
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                reqFTP.Proxy = null;
                reqFTP.UsePassive = false;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream responseStream = response.GetResponseStream();
                FileStream writeStream = new FileStream(dest + file, FileMode.Create);
                int Length = 2048;
                Byte[] buffer = new Byte[Length];
                int bytesRead = responseStream.Read(buffer, 0, Length);
                while (bytesRead > 0)
                {
                    writeStream.Write(buffer, 0, bytesRead);
                    bytesRead = responseStream.Read(buffer, 0, Length);
                }
                writeStream.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                CreateLogFile.MessageLog(ex.Message);
                Flag = false;
            }

        }

        //For Sending Email
        private static void SendEmail(String Fname)
        {

            MailMessage mail = new MailMessage();
            mail.Subject = "File downloaded from abc";
            mail.From = new MailAddress("abc@gmail.com");
            mail.To.Add("abc@gmail.com");
            mail.Body = "Hello! your file has been Downloaded from FTP...";

            SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
            smtp.EnableSsl = true;
            NetworkCredential netCre = new NetworkCredential("abc@gmail.com", "12345678");
            smtp.Credentials = netCre;

            try
            {
                smtp.Send(mail);
            }
            catch (Exception ex)
            {
                CreateLogFile.MessageLog(ex.Message);
                Flag = false;
            }

        }

        public static void DeleteFileOnServer(string file)
        {
            try
            {
                string uri = ConfigurationManager.AppSettings["FTPDirectory"] + file;
                // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
                if (!ftpAnnonymous)
                {
                    request.Credentials = new NetworkCredential(ftpUserName, ftpUserPassword);
                }
                request.Method = WebRequestMethods.Ftp.DeleteFile;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                CreateLogFile.MessageLog("Delete from FTPserver status: {0}" + response.StatusDescription);
                response.Close();
            }
            catch (Exception ex)
            {
                CreateLogFile.MessageLog("Deleting File" + ex.Message);
            }
        }
    }
}

app.config:
---------------

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key ="LocalDestination" value="D:\Test\Local destintaion_1\"/>   
     <add key="FTPDirectory" value="ftp://192.168.1.7/Raju/"/>
    <add key="FTPuserName" value="abc"/>
    <add key="FTPpassword" value="1234"/>
    <add key="FTPanonymous?" value="false"/>
   
  

    <add key="FromEmail" value="abc@gmail.com"/>
    <add key="ToEmail" value="abc@gmail.com"/>
    <add key="Host" value="smtp.gmail.com"/>
    <add key="Port" value="587"/>
    <add key="Password" value="111111"/>

    <add key="Logpath" value="D:\Test\log_download\"/>

  
   
  </appSettings>
</configuration>

Logfile Creation:
-------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace DownloadRMAfromDCL
{
    class CreateLogFile
    {
        private static string LogFormat;
        private static string ErrorTime;
        public static string LogPath = ConfigurationManager.AppSettings["Logpath"];


        //For Creating Log File
        public static void MessageLog(string sErrMsg)
        {
            LogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";
            ErrorTime = DateTime.Now.ToString("yyyyMMdd");
            StreamWriter sw = new StreamWriter(LogPath + "FTP Download job" + ErrorTime + ".txt", true);
            sw.WriteLine(LogFormat + sErrMsg);
            sw.Flush();
            sw.Close();
        }
    }
}



No comments:

Post a Comment