c#隐式从没有第三方库的ftp服务器下载文件

时间:2014-11-25 20:35:03

标签: c# ftp

我试图隐式连接到ftp服务器以下载文件。我在建立连接时遇到了麻烦。这是我正在尝试的。

using (TcpClient client = new TcpClient("ftp://server/", 990))
  using (SslStream sslStream = new SslStream(client.GetStream(), true))
  {
    // Start SSL/TLS Handshake
    sslStream.AuthenticateAsClient("localhost");

    // Setup a delegate for writing FTP commands to the SSL stream
    Action<string> WriteCommand = delegate(string command)
    {
      byte[] commandBytes =
          Encoding.ASCII.GetBytes(command + Environment.NewLine);
      sslStream.Write(commandBytes, 0, commandBytes.Length);
    };

    // Write raw FTP commands to the SSL stream
    WriteCommand("USER user");
    WriteCommand("PASS password");

    // Connect to data port to download the file 
  }

我需要什么:

  

1)隐式建立ftp服务器连接的代码

     

2)通过此连接下载文件的代码

6 个答案:

答案 0 :(得分:1)

   using (TcpClient client = new TcpClient("ftp://server/", 990))

端口990是FTPS protocol的控制端口的已分配端口号。正如您所描述的那样,这是一种使用TLS或SSL加密传输文件的方法。希望前者,自POODLE attack被揭露以来不再使用SSL了。编写自己的客户端是不寻常的,这当然已经在以前完成。

您的问题非常清楚您认为自己需要编写自己的客户的原因。因此,正确的答案可能很简单,您可能会忽略FTPS支持已经内置于.NET Framework中。

使用FtpWebRequest.EnableSsl属性。

答案 1 :(得分:0)

SslStream不能用于ftp,只能用于ssl。

您可以使用FtpWebRequest类通过ftp检索数据:

http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest%28v=vs.110%29.aspx

上面链接中的文章有几个例子,其中一个是从ftp服务器下载ftp文件:

public static bool DisplayFileFromServer(Uri serverUri)
{
    // The serverUri parameter should start with the ftp:// scheme. 
    if (serverUri.Scheme != Uri.UriSchemeFtp)
    {
        return false;
    }
    // Get the object used to communicate with the server.
    WebClient request = new WebClient();

    // This example assumes the FTP site uses anonymous logon.
    request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
    try 
    {
        byte [] newFileData = request.DownloadData (serverUri.ToString());
        string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
        Console.WriteLine(fileString);
    }
    catch (WebException e)
    {
        Console.WriteLine(e.ToString());
    }
    return true;
}

答案 2 :(得分:0)

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            Console.WriteLine(reader.ReadToEnd());

            Console.WriteLine("Download Complete, status {0}", response.StatusDescription);

            reader.Close();
            response.Close();  
        }
    }
}

取自 http://msdn.microsoft.com/en-us/library/vstudio/ms229711%28v=vs.100%29.aspx

答案 3 :(得分:0)

您已经说过,您不想购买第三方库来实现这一目标,但有an FTP client implementation at CodePlex声称支持FTPS。

它的MIT已获得许可,因此如果您不愿意引入第三方依赖关系,您可以查看源代码,看看是否有任何可以使用的实现。

答案 4 :(得分:0)

您可以使用此代码:

public void DownloadFromFTP( string ftpLocation, string fileName, string localFolder, string login, string password )
{
    var remoteFilePath = ftpLocation + @"/" + fileName;

    FtpWebResponse response = null;

    try
    {
        var request = (FtpWebRequest)WebRequest.Create( new Uri( remoteFilePath ) );
        request.Method = WebRequestMethods.Ftp.DownloadFile;
        request.Credentials = new NetworkCredential( login, password );

        response = (FtpWebResponse)request.GetResponse();

        var stream = response.GetResponseStream();

        var localPath = string.Format( @"{0}\{1}", localFolder, fileName );

        using( var fs = File.Create( localPath ) )
        {
            stream.CopyTo( fs );
        }
    }
    catch( Exception ex )
    {
        throw ex;
    }
    finally
    {
        if( response != null )
        {
            response.Close();
        }
    }
}

答案 5 :(得分:0)

更改以下行,我相信您应该可以连接。

using (TcpClient client = new TcpClient("ftp://server/", 990))

将以上行更改为:

using (TcpClient client = new TcpClient("server", 990))

还尝试使用默认FTP端口21:

using (TcpClient client = new TcpClient("server", 21))