列出FTP服务器中目录的文件. [英] Listing files of a directory from FTP server..

查看:92
本文介绍了列出FTP服务器中目录的文件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);
    }


调试时,出现以下错误:

错误:对象引用未设置为对象的实例.

在foreach语句中指向"in"

[edit] rjm:添加了< pre></pre>标签以澄清代码.[/edit]


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]

推荐答案

您得到的错误是什么?


我注意到您正在使用try/catch,但在catch块中不执行任何操作.这意味着任何错误都将被忽略.至少您应该在catch块中发布一条消息,显示错误详细信息.您还应该检查方法的结果是否实际返回了期望的数据.

您收到的错误消息表明某些对象尚未正确初始化.可能是由于缺少错误检查所致.
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.


这篇关于列出FTP服务器中目录的文件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆