URI空格被转换为"%20"使用WebClient.DownloadData

时间:2018-01-02 18:09:56

标签: c# download ftp

我正在尝试使用WebClient类通过FTP下载文件。 问题是,包含FTP服务器上文件路径的目录之一包含空格。

而且,即使我的URI字符串有空格,它们都被转换为"%20"使用DownloadData方法时自动,因此找不到目录,下载失败。

我的问题是:有没有办法强制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.

3 个答案:

答案 0 :(得分: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";

(问题与空格无关)

答案 1 :(得分: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)被宣布为过时,因此可能会在某个时候将其从框架中删除。

答案 2 :(得分:-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);
 }