1

我有以下代码从我的 FTP 服务器读取项目:

internal List<FtpItem> OpenFolder(string folderName)
{
   FtpWebRequest request = CreateFtpWebRequest("ftp://myserver.com", folderName);
   request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
   List<FtpItem> ftpItems = GetFtpItemsFromRequest(request);
   return ftpItems;
}

private List<FtpItem> GetFtpItemsFromRequest(FtpWebRequest ftpWebRequest)
{
   List<FtpItem> ftpItems = new List<FtpItem>();
   WebResponse webResponse = ftpWebRequest.GetResponse();
   StreamReader reader = new StreamReader(webResponse.GetResponseStream());
   string line = reader.ReadLine();
   while (line != null)
   {
      ftpItems.Add(new FtpItem(line));
      line = reader.ReadLine();
   }
   reader.Close();
   webResponse.Close();
   return ftpItems;
}   

private FtpWebRequest CreateFtpWebRequest(params string[] url)
{
   FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(string.Join("/", url));
   webRequest.KeepAlive = false;
   webRequest.UseBinary = true;
   webRequest.Credentials = this.networkCredential;
   return webRequest;
}

只要我尝试打开一个文件夹,root/sub/subsub一切正常。但如果文件夹名称包含空格,我会收到错误消息

No such file or directory

我试图用 %20 替换空格字符,但这不起作用。

我必须做什么才能打开包含空格的文件夹?

4

1 回答 1

5

您在 url 请求的末尾忘记了一个结束“/”。因此,要么将其附加到请求的末尾:

FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(string.Join("/", url)+"/");

或添加一个空字符串作为 url 参数:

FtpWebRequest request = CreateFtpWebRequest("ftp://myserver.com", folderName,"");
于 2013-07-21T17:31:10.497 回答