【发布时间】:2018-01-02 18:09:55
【问题描述】:
我正在尝试使用 WebClient 类通过 FTP 下载文件。 问题是,FTP 服务器上包含文件路径的目录之一包含空格。
而且,即使我的 URI 字符串有空格,但在使用 DownloadData 方法时,它们都会自动转换为“%20”,因此找不到目录,下载失败。
我的问题是:有没有办法强制 WebClient 不将我的空格转换为 %20 ?
这是我的代码:
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential("login", "password");
string url = ("ftp://XXX.XXX.XX.XXX:21/root/folder1/folder with spaces/pic1.jpg");
byte[] fileData = request.DownloadData(url);
using (FileStream file = File.Create(localpath))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
}
使用 Wireshark,这是我的网络日志:
Request: USER login
Response: 331 Please specify the password
Request: PASS password
Response: 230 Login successful
Request: OPTS utf8 on
Response: 200 Always in UTF8 mode.
Request: PWD
Response: 257 "/home/login"
Request: CWD home/login/root/folder1/folder%20with%20spaces/
Response: 550 Failed to change directory
尝试下载文件夹 1 的日志(请注意,CWD 没有失败,我只是收到一个错误,因为它需要的是文件而不是文件夹):
Response: 230 Login successful
Request: OPTS utf8 on
Response: 200 Always in UTF8 mode.
Request: PWD
Response: 257 "/home/login"
Request: CWD home/login/root/
Response: 250 Directory successfully changed
Request: RETR folder1
Response: 550 Failed to open file.
使用FileZilla下载pic1.jpg的日志(注意区别是文件路径中没有%20):
Response: 230 Login successful
Request: OPTS UTF8 on
Response: 200 Always in UTF8 mode.
Request: CWD home/login/root/folder1/folder with spaces/
Response: 250 Directory successfully changed
Request: RETR pic1.jpg
Response: 150 Opening BINARY mode data connection for pic1.jpg
Response: 226 Transfer complete.
【问题讨论】:
-
您可以在将值用作文件路径之前对值进行 URL 解码。
-
filePath的值是什么? + 你遇到了什么异常? -
filePath is "/folder1/folder with spaces/picture.jpg" 异常是“WebException: Server returned an error: 550 Failed to change directory”
-
如果您只是将示例代码中的
filePath替换为包含空格的实际路径会更明显。