如何在没有凭据的情况下连接ftp服务器?

时间:2017-12-02 08:03:59

标签: c# ftp

输入用户名/密码以连接带有凭据的ftp服务器时出现问题:

request.Credentials = new NetworkCredential(UserName, Password);

但是当尝试连接ftp服务器时,用户名/密码嵌入地址问题就解决了:

ftp://usernamae:password@192.168.1.1:21

如何在我的代码中使用这种格式来连接ftp服务器:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

例如:

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://username:password@ftp.example.com/remote/path/file.zip");
request.Method = WebRequestMethods.Ftp.DownloadFile;

using (Stream ftpStream = request.GetResponse().GetResponseStream())
using (Stream fileStream = File.Create(@"C:\local\path\file.zip"))
{
    byte[] buffer = new byte[10240];
    int read;
    while ((read = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
    {
        fileStream.Write(buffer, 0, read);
        Console.WriteLine("Downloaded {0} bytes", fileStream.Position);
    }
}

0 个答案:

没有答案