Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

C#
private void Download()
        {
            Uri url = new Uri("ftp://"+FtpAddress+"/filename");
            if (url.Scheme == Uri.UriSchemeFtp)
            {
                FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
                //Set credentials if required else comment this Credential code
                NetworkCredential objCredential = new NetworkCredential(sFtpUsername,sFtpPassword);
                objRequest.Credentials = objCredential;
                objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
                StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
                byte[] buffer = new byte[16 * 1024];
                int len = 0;
                FileStream objFS = new FileStream("Test.jpg", FileMode.Create, FileAccess.Write, FileShare.Read);
                while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    objFS.Write(buffer, 0, len);
                }
                objFS.Close();
                objResponse.Close();
            }
        }

I use the above code to download files from FTP server. I am able to download the files not .zip,.rar files. How to download .zip,.rar files from FTP please help me to solve this issue. When I try to download .zip file, I get the following error The remote server returned an error: (502) Bad Gateway.
Posted
Updated 5-Jul-13 0:36am
v2
Comments
Prasad Khandekar 5-Jul-13 7:42am    
Hello,

Try putting following lines immediately after line objRequest.Method = WebRequestMethods.Ftp.DownloadFile;

objRequest.UsePassive = false;
objRequest.Proxy = null;

Regards,

Try bellow code, it works perfectly for me
C#
public static List<periodicalfile> GetFTPFilesPath(string ftpAddress, string UserName, string Password)
        {
           
            FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpAddress);

            try
            {
                reqFTP.UsePassive = true;
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                reqFTP.Credentials = new NetworkCredential(UserName, Password);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

                Stream responseStream = response.GetResponseStream();
                List<string> files = new List<string>();
                StreamReader reader = new StreamReader(responseStream);
                while (!reader.EndOfStream)
                    files.Add(reader.ReadLine());
                reader.Close();
                responseStream.Dispose();
                
                //Loop through the resulting file names.
                string ftpPath = string.Empty;
                foreach (var fileName in files)
                {
                    var parentDirectory = "";
                    PeriodicalFile lstFile = new PeriodicalFile();
                    //If the filename has an extension, then it actually is 
                    //a file            
                    if (fileName.Contains(".zip"))
                    {
                        ftpPath = ftpAddress + fileName;
                        lstFile.FTPFileName = ftpPath;
                        listAllFTPFolder.Add(lstFile);
                    }
                    else
                    {
                        //If the filename has no extension, then it is just a folder. 
                        //Run this method again as a recursion of the original:
                        parentDirectory += fileName + "/";
                        try
                        {
                            GetFTPFilesPath(ftpAddress + "/" + parentDirectory, UserName, Password);
                        }
                        catch (Exception ex)
                        {
                            ErrorLog.WriteLog("ftpFileProcessing", "GetFTPFilesPath(Else)", ex.Message, ex.StackTrace, "");
                        }
                    }
                }
                
            }
            

            catch (Exception excpt)
            {

                reqFTP.Abort();
                ErrorLog.WriteLog("ftpFileProcessing", "GetFTPFilesPath", excpt.Message, excpt.StackTrace, "");

            }


            return listAllFTPFolder;
 
Share this answer
 
v2
Comments
sacraj 5-Jul-13 6:40am    
What is the Visual studio version that you are using. I am using Visual studio 2010. Do I need to give any reference. When I paste the above code code compile time error.
Mukesh Ghosh 5-Jul-13 6:47am    
I also in VS 2010. Can you give me what kind of error you get? You might need to add some reference.
sacraj 5-Jul-13 6:51am    
the type or namespace name 'PeriodicalFile' could not be found
Try this,,,:)

C#
Uri url = new Uri("ftp://ftp.demo.com/file1.txt");
if (url.Scheme == Uri.UriSchemeFtp)
{
    FtpWebRequest objRequest = (FtpWebRequest)FtpWebRequest.Create(url);
    //Set credentials if required else comment this Credential code
    NetworkCredential objCredential = new NetworkCredential("FTPUserName", "FTPPassword");
    objRequest.Credentials = objCredential;
    objRequest.Method = WebRequestMethods.Ftp.DownloadFile;
    FtpWebResponse objResponse = (FtpWebResponse)objRequest.GetResponse();
    StreamReader objReader = new StreamReader(objResponse.GetResponseStream());
    byte[] buffer = new byte[16 * 1024];
    int len = 0;
    FileStream objFS = new FileStream(Server.MapPath("file1.txt"), FileMode.Create, FileAccess.Write, FileShare.Read);
    while ((len = objReader.BaseStream.Read(buffer, 0, buffer.Length)) != 0)
    {
        objFS.Write(buffer, 0, len);
    }
    objFS.Close();
    objResponse.Close();
}



http://www.vcskicks.com/download-file-ftp.php[^]
 
Share this answer
 
Comments
sacraj 5-Jul-13 6:41am    
I am able to download .txt file, but not able to download .zip file from FTP Server.
Nirav Prabtani 5-Jul-13 6:56am    
it means u able to download .zip file right??
You do not need this. please modify as per your requirement, i am posting this again, changes as per your requirement
C#
public static void DownloadFTPFiles(string ftpAddress, string UserName, string Password)
{
    FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpAddress);

    try
    {
        reqFTP.UsePassive = true;
        reqFTP.UseBinary = true;
        reqFTP.KeepAlive = false;
        reqFTP.Credentials = new NetworkCredential(UserName, Password);
        reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

        Stream responseStream = response.GetResponseStream();
        List<string> files = new List<string>();
        StreamReader reader = new StreamReader(responseStream);
        while (!reader.EndOfStream)
            files.Add(reader.ReadLine());
        reader.Close();
        responseStream.Dispose();
        List<periodicalfile> lstFiles = new List<periodicalfile>();
        //Loop through the resulting file names.
        string ftpPath = string.Empty;
        foreach (var fileName in files)
        {
            var parentDirectory = "";                   
            if (fileName.Contains(".zip"))
            {
                ftpPath = ftpAddress + fileName;
                wc.Credentials = new NetworkCredential(UserName, Password);
                wc.DownloadFile(file.FTPFileName, DestinationFolder + fileName);//DOWLOAD FROM FTP
            }
            else
            {
                //If the filename has no extension, then it is just a folder. 
                //Run this method again as a recursion of the original:
                parentDirectory += fileName + "/";
                try
                {
                    DownloadFTPFiles(ftpAddress + "/" + parentDirectory, UserName, Password);
                }
                catch (Exception ex)
                {
                    ErrorLog.WriteLog("ftpFileProcessing", "DownloadFTPFiles(Else)", ex.Message, ex.StackTrace, "");
                }
            }
        }
    }
    catch (Exception excpt)
    {
        reqFTP.Abort();
        ErrorLog.WriteLog("ftpFileProcessing", "DownloadFTPFiles", excpt.Message, excpt.StackTrace, "");
    }
}
 
Share this answer
 
v2
Comments
sacraj 5-Jul-13 7:13am    
wc what is this, it gives me an error
Mukesh Ghosh 5-Jul-13 7:18am    
Add this
WebClient wc = new WebClient();
sacraj 5-Jul-13 7:29am    
hi,
I am able to download .jpg,.gif and other types but not able to download .Zip file, When I download .zip I get the following error," The remote server returned an error: (502) Bad Gateway."
Mukesh Ghosh 5-Jul-13 7:36am    
Well, there must be some restriction for Zip in FTP server, check for that.
sacraj 8-Jul-13 1:29am    
Yes, I had the problem with proxy of my server. Thanks for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900