从ftpserver下载文件时出现异常

时间:2015-01-19 13:01:20

标签: c# ftp

我使用下面的代码将文件从FTP服务器下载到本地文件系统。但是,当我使用它时,它显示以下错误

Exception thrown while running the code

我使用了以下代码

代码段

private string user = "uname";
private string pass = "passwd";
private FtpWebRequest ftpRequest ;
private FtpWebResponse ftpResponse ;
private Stream ftpStream ;



public void download(string remoteFile, string localFile)
{
    try
    {

        ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://uname:passwd@hostname/foldername/filename");

        ftpRequest.Credentials = new NetworkCredential(user, pass);

        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = false;


        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

        ftpStream = ftpResponse.GetResponseStream();

        FileStream localFileStream = new FileStream(localFile, FileMode.Create);

        byte[] byteBuffer = new byte[2048];
        int bytesRead = ftpStream.Read(byteBuffer, 0, 2048);

        try
        {
            while (bytesRead > 0)
            {
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
            }
        }
        catch (Exception ex) { Console.WriteLine(ex.ToString()); }

        localFileStream.Close();
        ftpStream.Close();
        ftpResponse.Close();
    }
    catch (Exception ex)
    {

        Console.WriteLine(ex.ToString());
        Console.ReadKey();
    }
    return;
}

有人可以帮我解决这个问题吗?

更新

我还将ftpRequest.KeepAlive = false;更改为ftpRequest.KeepAlive = true;

但我面临同样的例外

2 个答案:

答案 0 :(得分:0)

ftpRequest.KeepAlive = false;更改为ftpRequest.KeepAlive = true;

答案 1 :(得分:0)

当我更改下面的代码时

 ftpRequest.UsePassive = false;

从ftp服务器下载给定文件