【发布时间】:2011-06-02 20:33:52
【问题描述】:
我正在编写一个使用带有凭据的 ftp 服务器的程序。我正在尝试从服务器检索目录列表,但是当我到达线路时:
string line = reader.ReadLine();
我得到的字符串只包含:“无法打开\”host:/lib1\”。”
如果我尝试获取另一行,则会引发下一个异常:远程服务器返回错误:(550) 文件不可用(例如,找不到文件,无法访问)。
我确信(使用另一个 ftp 应用程序)'lib1' 目录存在于 ftp 服务器上,并且我的凭据(用户名和密码)是正确的。
这是我的代码:
public class FTPClient
{
public string UserName { get; set; }
public string Password { get; set; }
public string IpAddress { get; set; }
public int Port { get; set; }
public FTPClient(string _userName, string _password, string _address, int _port)
{
UserName = _userName;
Password = _password;
IpAddress = _address;
Port = _port;
}
public void GetDirectoriesList(string _path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" +
IpAddress + _path));
request.UseBinary = true;
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(UserName, Password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string line = reader.ReadLine();
while (line!=null)
{
... //do something with line
line = reader.ReadLine();
}
...
reader.Close();
response.Close();
}
我使用它如下:
FTPClient ftpClient = new FTPClient("user1", "pass1", "192.168.2.110", 21);
string dirList = ftpClient.GetDirectoriesList("/lib1");
谁能发现问题?
【问题讨论】:
-
关于从 C# 中的 FTP 服务器获取目录列表的更一般的问题:stackoverflow.com/questions/3298922/…
-
使用证书的自定义验证,见stackoverflow.com/questions/5109752/…
-
这个问题很不清楚 - 您只是在寻求一种使用凭据连接到 FTP 服务器的方法,还是让我们调试此特定代码?您是否愿意接受使用库的解决方案,例如 FluentFTP?阅读第一行是否会给您一个不正确的结果(您在第二句话中所说的内容)或抛出异常(当您说第二个
ReadLine调用抛出 another 异常时所暗示的意思)?这里有太多无法修复的错误;我投票结束。 -
我投票决定将此问题作为题外话来结束,因为目前还不清楚出了什么问题,而且似乎它可能与 OPs 环境或他们正在连接的服务器非常特定到。因此,很难给出明确的答案,而且将来很可能对其他人没有帮助。
-
我在您的代码中唯一没有看到的是您在请求 Uri 中将端口号附加到您的 IP 地址的位置?我不是 100% 确定这是问题所在,但仅通过查看您发布的内容,您返回的部分错误看起来像这样:“host:/lib1”这使得它看起来主机和冒号在冒号后显示您的 Uri 但没有端口号。那么问题可能只是您请求 Uri 的格式?
标签: c# ftp ftpwebresponse