Monday, May 12, 2025

Breaking News
>> Securing and encrypt View State and Cookies values  >> Page has one or more controls that do not correspond with   >> “The Controls collection cannot be modified because the control contains code blocks”  >> How to fix "Validation(): Element 'xxxx' is not supported  >> How to create a new session in ASP.NET programmatically  >> MySQL Database Backup using mysqldump command    

Editors Picks

Tuesday, November 8, 2011

how to download file from ftp using c#


public bool Download(string filePath, string fileName)
    {
       
        FtpWebRequest reqFTP;
        try
        {
            string ftpServerIP =”ftpservernane”;
            //filePath = <>,
            //fileName = <>
            FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
            string uri = "ftp://" + ftpServerIP + "/" + fileName;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileName));
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential("", "");
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream ftpStream = response.GetResponseStream();
            long cl = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];

            if (ftpFileExist(uri))
            {
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
             
                return true;
            }
            else
            { return false; }
        }
        catch (Exception ex)
        {
            return false; //MessageBox.Show(ex.Message);
        }
    }
  public bool ftpFileExist(string fileName)
    {
        WebClient wc = new WebClient();
        try
        {
            wc.Credentials = new NetworkCredential("", "");
            byte[] fData = wc.DownloadData(fileName);
            if (fData.Length > -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            // Debug here?
        }
        return false;
    }

No comments :

Post a Comment

Contact Us

Name

Email *

Message *