无法打开带空格的文件夹

时间:2013-07-21 16:00:53

标签: c# ftpwebrequest

我有以下代码从我的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这样的文件夹,一切正常。但是如果foldername包含空格,我会收到错误消息

No such file or directory

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

如何打开包含空格的文件夹?

1 个答案:

答案 0 :(得分:5)

您在网址请求结束时忘记了结束“/”。所以要么将它附加到请求的末尾:

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

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

FtpWebRequest request = CreateFtpWebRequest("ftp://myserver.com", folderName,"");