Click here to Skip to main content
15,905,563 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
public class FileDownloader
{
    static void Main(string[] args)
    {
        string ftpServer = "ftp://ftp.******.com";
        string userName = "*****";
        string password = "******";
        string destionationLocation = @"D:\project\ss";           
        FileDownloader fDownloader = new FileDownloader();           
        List<string> collectionOfFiles =
            fDownloader.getFileList(ftpServer, userName, password);
        if (collectionOfFiles != null)
        {
            Console.WriteLine("if statement");
            Console.WriteLine(collectionOfFiles);
            foreach (string fileName in collectionOfFiles)
            {
                Console.WriteLine("for statment");                   
                string fullPathDestionation =
                    Path.Combine(destionationLocation, 
                    Path.GetFileNameWithoutExtension(fileName) + ".*");
                    fDownloader.downloadFile(ftpServer, fileName,
                        userName, password, fullPathDestionation);
            }
            Console.WriteLine("if statement closed");
        }
        else
        {
            Console.WriteLine("function is not called");
        }
        Console.WriteLine("downloaded successfully");
    }       
    public List<string> getFileList(string FTPAddress, string username, 
        string password)
    {
        List<string> files = new List<string>();
        Console.WriteLine("getting filelist");
        try
        {
            //Create FTP request
            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;
            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader reader =
                    new StreamReader(responseStream))
                {
                    while (!reader.EndOfStream)
                    {
                        files.Add(reader.ReadLine());
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // write to log
        }
        Console.WriteLine("fileslist got");
        return files;           
    }

    public void downloadFile(string FTPAddress,
                             string filename,
                             string username,
                             string password,
                             string destFile)
    {
        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.UsePassive = true;
            request.UseBinary = false;
            request.KeepAlive = false; //close the connection when done
            //Streams
            FtpWebResponse response = request.GetResponse()
                as FtpWebResponse;
            Stream reader = response.GetResponseStream();

            byte[] buffer = new byte[1024];
            using (Stream streamFile = File.Create(destFile))
            {
                while (true)
                {
                    int bytesRead = reader.Read(buffer, 0,
                        buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        streamFile.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // write to log
        }
        Console.WriteLine("downloaded");
    }
/*
I tried the above code to list the files of directory from ftp server
and then download them in c#.. but the following code does not
execute.. i dont know why.. can anybody help for me?
*/

    foreach (string fileName in collectionOfFiles)
    {
        Console.WriteLine("for statment");                   
        string fullPathDestionation =
            Path.Combine(destionationLocation,
            Path.GetFileNameWithoutExtension(fileName) + ".*");
        fDownloader.downloadFile(ftpServer, fileName, userName,
            password, fullPathDestionation);
    }

When I debug this I got the following error:

Error: Object reference not set to an instance of an object.

pointing "in" in foreach statement

[edit]rjm: added <pre></pre> tags to clarify code.[/edit]
Posted
Updated 2-Feb-10 8:51am
v3

I note that you are using try/catch but taking no action in the catch blocks. This means that any errors are being ignored. At the very least you should post a message in the catch block showing the error detail. You should also check the results of your methods are actually returning the data you expect.

The error message you received indicates that some object has not been initialised properly; chances are this is as a result of the lack of error checks.
 
Share this answer
 
what is the error your getting?
 
Share this answer
 

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