FtpWebRequest 下载文件

时间:2023-03-30
本文介绍了FtpWebRequest 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

The following code is intended to retrieve a file via FTP. However, I'm getting an error with it.

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

错误是:

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

The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

该文件确实存在于远程计算机上,我可以手动执行此 ftp(即我有权限).谁能告诉我为什么会出现这个错误?

The file definitely does exist on the remote machine and I am able to perform this ftp manually (i.e. I have permissions). Can anyone tell me why I might be getting this error?

推荐答案

本段来自FptWebRequest 类参考 您可能会感兴趣:

This paragraph from the FptWebRequest class reference might be of interest to you:

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

The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'), then the URI is absolute, and the current directory is /path. If, however, the URI is of the form "ftp://contoso.com/path", first the .NET Framework logs into the FTP server (using the user name and password set by the Credentials property), then the current directory is set to /path.

这篇关于FtpWebRequest 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:从 FTP 下载文件以及如何提示用户在 ASP.NET C# 中保存/打开文件 下一篇:如何检查FTP目录是否存在

相关文章