Welcome

Hello, Welcome to my blog. If you like feel free to refer others

Wednesday 8 April 2015

Last modified time of a file reside in FTP server

Add reference in your class:
using System.Net;
Then copy below mentioned method
 /// <summary>
        /// Get Server File TimeStamp
        /// </summary>
        /// <param name="serverPath"></param>
        /// <param name="userId"></param>
        /// <param name="password"></param>
        ///  <param name="fileName"></param>
        /// <returns></returns>
        ///
        public static DateTime GetServerFileTimestamp(string serverPath, string userId, string password, string fileName)
        {
            // Get the object used to communicate with the server.
            String serverUrl = String.Format("{0}{1}/{2}", @"ftp:", serverPath, fileName);
            Uri serverUri = new Uri(serverUrl);
            FtpWebRequest reqFTP = (FtpWebRequest)WebRequest.Create(serverUrl);
            reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;           
            reqFTP.Credentials = new NetworkCredential(userId, password);
            try
            {
                using (FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse())
                {
                    // Return the last modified time.
                    return response.LastModified;
                }
            }
            catch (Exception ex)
            {
                // If the file doesn't exist, return min date Otherwise rethrow the error.
                if (ex.Message.Contains("File unavailable"))
                    return DateTime.MinValue;
                throw;
            }
            finally
            {
                reqFTP = null;               
            }
        }

Above mentioned code  will return you last modified time.

Happy learning.............

Check ftp server is available or not

Add reference in your class:
using System.Net;
Then copy below mentioned method
/// <summary>
        /// GetServerAvailability to check ftp server is available or not
        /// </summary>
        /// <param name="userId">userId</param>
        /// <param name="password">password</param>
        /// <param name="ftpServerPath">ftpServerPath</param>
        /// <returns>status</returns>
        public static bool GetServerAvailability(string userId, string password, string ftpServerPath)
        {           
            FtpWebRequest reqFTP;
            bool isServerConnected = false;
            try
            {
                String serverUrl = String.Format("{0}{1}", @"ftp:", ftpServerPath);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(serverUrl));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    isServerConnected = true;
                }
               
            }
            catch (Exception ex)
            { 
                if (string.Compare(ex.GetType().ToString(), "System.Net.Sockets.SocketException", true) == 0)
                {
                    System.Net.Sockets.SocketException socketError = (System.Net.Sockets.SocketException)ex;
                    if (socketError.ErrorCode == 11004)
                        isServerConnected = false;
                }
                else
                {                   
                    isServerConnected = false;
                }
            }
            finally
            {
                reqFTP = null;
            }
            return isServerConnected;
        }

Above mentioned code will return you true if server is available else false.

Upload file into FTP server

Add 2 reference in your class:
using System.Net;
using System.IO;

Then copy below mentioned method

/// <summary>
        /// Upload Design File into FTP server
        /// </summary>
        /// <param name="serverPath"></param>
        /// <param name="localPath"></param>
        /// <param name="fileName"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public static bool UploadDesignFile(string serverPath, string localPath, string fileName,Dictionary<string,string> credentials)
        {           
            bool status = false;
          
            FtpWebRequest reqFTP;
            int bufferSize = 2048;
            try
            {
                String uploadUrl = String.Format("{0}{1}/{2}", @"ftp:", serverPath, fileName);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadUrl));
                 string username = string.Empty;
                credentials.TryGetValue("UserId",out username);
                string passwd = string.Empty;
                credentials.TryGetValue("Password",out passwd);
                reqFTP.Credentials = new NetworkCredential(Decrypt(username), Decrypt(passwd));
                reqFTP.UseBinary = true;
                reqFTP.UsePassive = true;
                reqFTP.KeepAlive = true;
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
               
                using (Stream uploadStream = reqFTP.GetRequestStream())
                {
                    string localFilePath = String.Format("{0}/{1}", localPath, fileName);
                    using (FileStream localFileStream = File.OpenRead(localFilePath))
                    {
                        /* Buffer for the Downloaded Data */
                        byte[] byteBuffer = new byte[localFileStream.Length];
                        int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                        /* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
                        try
                        {
                            while (bytesSent != 0)
                            {
                                uploadStream.Write(byteBuffer, 0, bytesSent);
                                bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
                            }
                            status = true;
                        }
                        catch (Exception ex)
                        {
                            status = false;
                        }
                    }
                }
               
            }
            catch (Exception ex)
            {
                status = false;
            }
            finally
            {               
                reqFTP = null;
            }
           
            return status;
        }


Above mentioned code will upload your file into FTP server. If file exists it will override that file.

Happy learning.....

Download file from FTP

Add 2 reference in your class:
using System.Net;
using System.IO;

Then copy below mentioned method
public static bool DownloadFile(string userId, string password, string ftpServerPath, string fileName, string localPath)
        {
            FtpWebRequest reqFTP;
            bool status = false;
            try
            {
                String downloadUrl = String.Format("{0}{1}/{2}", @"ftp:", ftpServerPath,fileName);
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(downloadUrl));
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(userId, password);
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.Proxy = null;
                reqFTP.KeepAlive = false;
                using (WebResponse response = reqFTP.GetResponse())
                {
                    using (Stream downloadStream = response.GetResponseStream())//;//read the download file from his stream
                    {
                        using (FileStream fs = File.Create(localPath + @"\" + fileName))
                        {
                            byte[] buffer = new byte[2048];
                            int read = 0;
                            do
                            {
                                read = downloadStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            }
                            while (read != 0);
                            status = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                status = false;
            }
            finally
            {               
                reqFTP = null;
            }
            return status;
        }

Above mentioned method will download the desired file from FTP server to your local file system.

Happy learning......