FtpWebRequest下载文件

Pau*_*els 35 .net c# ftp ftpwebrequest ftpwebresponse

以下代码旨在通过FTP检索文件.但是,我收到了一个错误.

serverPath = "ftp://x.x.x.x/tmp/myfile.txt";

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverPath);

request.KeepAlive = true;
request.UsePassive = true;
request.UseBinary = true;

request.Method = WebRequestMethods.Ftp.DownloadFile;                
request.Credentials = new NetworkCredential(username, password);

// Read the file from the server & write to destination                
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) // Error here
using (Stream responseStream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(responseStream))            
using (StreamWriter destination = new StreamWriter(destinationFile))
{
    destination.Write(reader.ReadToEnd());
    destination.Flush();
}
Run Code Online (Sandbox Code Playgroud)

错误是:

远程服务器返回错误:(550)文件不可用(例如,找不到文件,没有访问权限)

该文件肯定存在于远程计算机上,我可以手动执行此ftp(即我有权限).任何人都可以告诉我为什么我可能会收到此错误?

Mar*_*ram 49

我知道这是一个旧帖子,但我在这里添加以供将来参考.这是我找到的解决方案:

    private void DownloadFileFTP()
    {
        string inputfilepath = @"C:\Temp\FileName.exe";
        string ftphost = "xxx.xx.x.xxx";
        string ftpfilepath = "/Updater/Dir1/FileName.exe";

        string ftpfullpath = "ftp://" + ftphost + ftpfilepath;

        using (WebClient request = new WebClient())
        {
            request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
            byte[] fileData = request.DownloadData(ftpfullpath);

            using (FileStream file = File.Create(inputfilepath))
            {
                file.Write(fileData, 0, fileData.Length);
                file.Close();
            }
            MessageBox.Show("Download Complete");
        }
    }
Run Code Online (Sandbox Code Playgroud)

根据Ilya Kogan的出色建议更新

  • 如果你要使用`WebClient`,而不是`FtpWebRequest`,你可以使用它的[`DownloadFile`](http://msdn.microsoft.com/en-us/library/system.net.webclient .downloadfile.aspx)方法,而不是搞乱`FileStream`,这可能会更容易一些.但是WebClient有些东西不能做(比如使用`ACTV`而不是'PASV`FTP:`FtpWebRequest.UsePassive = false;`) (11认同)
  • 请注意,您应该处置IDisposable对象.最简单的方法是使用关键字"using". (4认同)

Fra*_*ack 23

您可能会对FptWebRequest类引用中这段内容感兴趣:

URI可以是相对的或绝对的.如果URI的格式为" ftp://contoso.com/%2fpath"(%2f是转义'/'),那么URI是绝对的,当前目录是/ path.但是,如果URI的格式为" ftp://contoso.com/path ",则首先.NET Framework登录到FTP服务器(使用Credentials属性设置的用户名和密码),然后是当前目录设置为/ path.


Mar*_*ryl 19

最简单的方法

使用.NET框架从FTP服务器下载二进制文件的最简单方法是使用WebClient.DownloadFile:

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.DownloadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");
Run Code Online (Sandbox Code Playgroud)

高级选项

FtpWebRequest仅当您需要更大的控件时才使用WebClient(不提供TLS/SSL加密,进度监控等).简单的方法是将FTP响应流复制到FileStream使用Stream.CopyTo:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    ftpStream.CopyTo(fileStream);
}
Run Code Online (Sandbox Code Playgroud)

进度监测

如果您需要监视下载进度,则必须自己按块复制内容:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关GUI进度(WinForms ProgressBar),请参阅:
使用ProgressBar进行FtpWebRequest FTP下载


正在下载文件夹

如果要从远程文件夹
下载所有文件,请参阅C#通过FTP下载所有文件和子目录.