如何使用c#winforms从ftp文件夹下载所有文件?

如何使用c#winforms从ftp文件夹下载所有文件?,c#,winforms,C#,Winforms,我想下载某个ftp文件夹的所有文件(该文件夹将变化=>variable),并将所有内容显示到ListView中 如何使用c#winforms实现这一点 我试过使用这个: public void download(string remoteFile, string localFile) { try { /* Create an FTP Request */ ftpRequest = (FtpWebRequest)FtpWebRequest.Creat

我想下载某个ftp文件夹的所有文件(该文件夹将变化=>variable),并将所有内容显示到ListView中

如何使用c#winforms实现这一点

我试过使用这个:

public void download(string remoteFile, string localFile)
{
    try
    {
        /* Create an FTP Request */
        ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
        /* Log in to the FTP Server with the User Name and Password Provided */
        ftpRequest.Credentials = new NetworkCredential(user, pass);
        /* When in doubt, use these options */
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        /* Specify the Type of FTP Request */
        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
        /* Establish Return Communication with the FTP Server */
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        /* Get the FTP Server's Response Stream */
        ftpStream = ftpResponse.GetResponseStream();
        /* Open a File Stream to Write the Downloaded File */
        FileStream localFileStream = new FileStream(localFile, FileMode.Create);
        /* Buffer for the Downloaded Data */
        byte[] byteBuffer = new byte[bufferSize];
        int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
        /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
        try
        {
            while (bytesRead > 0)
            {
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }
        /* Resource Cleanup */
        localFileStream.Close();
        ftpStream.Close();
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex) { Console.WriteLine(ex.ToString()); }
    return;
}

只下载1个指定文件。

要将所有文件从FTP目录下载到本地文件夹,您必须列出远程目录中的所有文件,然后逐个下载。您可以使用以下代码执行相同操作:

    string[] files = GetFileList();
    foreach (string file in files)
    {
        Download(file);
    }

    public string[] GetFileList()
    {
        string[] downloadFiles;
        StringBuilder result = new StringBuilder();
        WebResponse response = null;
        StreamReader reader = null;
        try
        {
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = false;
            response = reqFTP.GetResponse();
            reader = new StreamReader(response.GetResponseStream());
            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            if (reader != null)
            {
                reader.Close();
            }
            if (response != null)
            {
                response.Close();
            }                
            downloadFiles = null;
            return downloadFiles;
        }
    }

    private void Download(string file)
    {                       
        try
        {                
            string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;
            Uri serverUri = new Uri(uri);
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return;
            }       
            FtpWebRequest reqFTP;                
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDir + "/" + file));                                
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);                
            reqFTP.KeepAlive = false;                
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
            reqFTP.UseBinary = true;
            reqFTP.Proxy = null;                 
            reqFTP.UsePassive = false;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream responseStream = response.GetResponseStream();
            FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);                
            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);               
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
            }                
            writeStream.Close();
            response.Close(); 
        }
        catch (WebException wEx)
        {
            MessageBox.Show(wEx.Message, "Download Error");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Download Error");
        }
    }

参考:

要将所有文件从FTP目录下载到本地文件夹,您必须列出远程目录中的所有文件,然后逐个下载。您可以使用以下代码执行相同操作:

    string[] files = GetFileList();
    foreach (string file in files)
    {
        Download(file);
    }

    public string[] GetFileList()
    {
        string[] downloadFiles;
        StringBuilder result = new StringBuilder();
        WebResponse response = null;
        StreamReader reader = null;
        try
        {
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = false;
            response = reqFTP.GetResponse();
            reader = new StreamReader(response.GetResponseStream());
            string line = reader.ReadLine();
            while (line != null)
            {
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            if (reader != null)
            {
                reader.Close();
            }
            if (response != null)
            {
                response.Close();
            }                
            downloadFiles = null;
            return downloadFiles;
        }
    }

    private void Download(string file)
    {                       
        try
        {                
            string uri = "ftp://" + ftpServerIP + "/" + remoteDir + "/" + file;
            Uri serverUri = new Uri(uri);
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return;
            }       
            FtpWebRequest reqFTP;                
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDir + "/" + file));                                
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);                
            reqFTP.KeepAlive = false;                
            reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;                                
            reqFTP.UseBinary = true;
            reqFTP.Proxy = null;                 
            reqFTP.UsePassive = false;
            FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
            Stream responseStream = response.GetResponseStream();
            FileStream writeStream = new FileStream(localDestnDir + "\" + file, FileMode.Create);                
            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);               
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
            }                
            writeStream.Close();
            response.Close(); 
        }
        catch (WebException wEx)
        {
            MessageBox.Show(wEx.Message, "Download Error");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Download Error");
        }
    }

参考资料:

我发现WebClient方法更易于使用:

        string downloadPath = Application.StartupPath;
        string ftpID = "userid";
        string password = "password";
        string fileSource = "ftp://yoursite.com/site/ftproot/somedirectory/somefile.ext";
        string fileDest = $"{downloadPath}\\somefile.ext";

        WebClient client = new WebClient();
        client.Credentials = new NetworkCredential(ftpID, password);
        client.DownloadFile(fileSource, fileDest);

我发现WebClient方法更易于使用:

        string downloadPath = Application.StartupPath;
        string ftpID = "userid";
        string password = "password";
        string fileSource = "ftp://yoursite.com/site/ftproot/somedirectory/somefile.ext";
        string fileDest = $"{downloadPath}\\somefile.ext";

        WebClient client = new WebClient();
        client.Credentials = new NetworkCredential(ftpID, password);
        client.DownloadFile(fileSource, fileDest);

更新了我的问题更新了我的问题
responseStream.Read
应该在while循环中。在关闭响应之前,responseStream也可以显式关闭。
responseStream.Read
应该在while循环中。在关闭响应之前,还可以显式关闭responseStream。