使用WebClient.DownloadData将URI空格转换为“%20”

问题描述 投票:1回答:3

我正在尝试使用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 

登录尝试下载folder1(注意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.
c# download ftp
3个回答
0
投票

如果需要访问与主文件夹不相关的路径,则需要使用两个斜杠:

string url = "ftp://XXX.XXX.XX.XXX:21//root/folder1/folder with spaces/pic1.jpg";

或相对路径如:

string url = "ftp://XXX.XXX.XX.XXX:21/../../root/folder1/folder with spaces/pic1.jpg";

(问题与空间无关)


0
投票

你能尝试用Uri手动创建你的Uri(string, bool)吗?

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";
    var uri = new Uri(url, true);
    byte[] fileData = request.DownloadData(uri);
    using (FileStream file = File.Create(localpath))
    {
        file.Write(fileData, 0, fileData.Length);
        file.Close();
    }
}

请注意,Uri(string, bool)被宣布为过时,因此可能会在某些时候将其从框架中删除。


-3
投票

如果有理由你没有使用WebClient.DownloadFile?

using (WebClient request = new WebClient())
{
   request.Credentials = new NetworkCredential("login", "password");
   string url = ("ftp://XXX.XXX.XX.XXX:21/root" + filePath);
   request.DownloadFile(url, localpath);
 }
© www.soinside.com 2019 - 2024. All rights reserved.