首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果可能在FtpWebRequest中使用C#实现没有第三方dll的FTP/SFTP

如果可能在FtpWebRequest中使用C#实现没有第三方dll的FTP/SFTP
EN

Stack Overflow用户
提问于 2012-05-18 17:46:36
回答 3查看 37.1K关注 0票数 16

我试图通过FtpWebRequest类在C#中实现ftp/sftp,但到目前为止还没有成功。

我不想使用任何第三方免费或付费dll。

凭据就像

  1. 主机名= sftp.xyz.com
  2. userid = abc
  3. 密码= 123

我能够用Ip地址实现ftp,但不能使用凭据来获得上述主机名的sftp。

对于sftp,我已经启用了FtpWebRequest类的FtpWebRequest属性为true,但得到的错误无法连接到远程服务器。

我能够使用相同的凭据和主机名与Filezilla连接,但不能通过代码连接。

我观察到filezilla,它在文本框中将主机名从ftp://sftp.xyz.com更改为s sftp.xyz.com,在命令行中将userid更改为abc@sftp.xyz.com。

我在代码中也这样做过,但是对于sftp没有成功。

这件事需要紧急帮助。提前谢谢。

下面是到目前为止我的代码:

代码语言:javascript
运行
复制
private static void ProcessSFTPFile()
{
    try
    {
        string[] fileList = null;
        StringBuilder result = new StringBuilder();

        string uri = "ftp://sftp.xyz.com";

        FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(uri));
        ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        ftpRequest.EnableSsl = true;
        ftpRequest.Credentials = new NetworkCredential("abc@sftp.xyz.com", "123");
        ftpRequest.UsePassive = true;
        ftpRequest.Timeout = System.Threading.Timeout.Infinite;

        //ftpRequest.AuthenticationLevel = Security.AuthenticationLevel.MutualAuthRequested;
        //ftpRequest.Proxy = null;
        ftpRequest.KeepAlive = true;
        ftpRequest.UseBinary = true;

        //Hook a callback to verify the remote certificate 
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
        //ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true);

        FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream());
        string line = reader.ReadLine();
        while (line != null)
        {
            result.Append("ftp://sftp.xyz.com" + line);
            result.Append("\n");
            line = reader.ReadLine();
        }

        if (result.Length != 0)
        {
            // to remove the trailing '\n'
            result.Remove(result.ToString().LastIndexOf('\n'), 1);

            // extracting the array of all ftp file paths
            fileList = result.ToString().Split('\n');
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
        Console.ReadLine();
    }
}

public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
    if (certificate.Subject.Contains("CN=sftp.xyz.com"))
    {
        return true;
    }
    else
    {
        return false;
    }
}
EN

回答 3

Stack Overflow用户

发布于 2015-03-27 13:27:55

更新:

如果使用BizTalk,可以使用SFTP适配器。,则使用ESB工具包。它自2010年以来一直得到支持。有人想知道为什么它没能到达.Net Framework

  1. BizTalk Server 2013:以ESB创建自定义适配器提供程序为例
  2. BizTalk Server 2013:如何使用SFTP适配器
  3. MSDN文档

--

不幸的是,它仍然需要做大量的工作,只是目前的框架。放置sftp协议前缀不足以使make-it-work仍然没有内置的.Net框架支持,也许在将来。

---------------------------------------------------------

1)一个很好的试用库是SSHNet.

---------------------------------------------------------

它包括:

  1. 更多的功能,包括内置的流支持。
  2. API文档
  3. 一个可以用来编写代码的简单API

文档中的示例代码:

列表目录

代码语言:javascript
运行
复制
/// <summary>
/// This sample will list the contents of the current directory.
/// </summary>
public void ListDirectory()
{
    string host            = "";
    string username        = "";
    string password        = "";
    string remoteDirectory = "."; // . always refers to the current directory.

    using (var sftp = new SftpClient(host, username, password))
    {
        sftp.Connect();

        var files = sftp.ListDirectory(remoteDirectory);
        foreach (var file in files)
        {
            Console.WriteLine(file.FullName);
        }
    }
}

上传文件

代码语言:javascript
运行
复制
/// <summary>
/// This sample will upload a file on your local machine to the remote system.
/// </summary>
public void UploadFile()
{
    string host           = "";
    string username       = "";
    string password       = "";
    string localFileName  = "";
    string remoteFileName = System.IO.Path.GetFileName(localFile);

    using (var sftp = new SftpClient(host, username, password))
    {
        sftp.Connect();

        using (var file = File.OpenRead(localFileName))
        {
            sftp.UploadFile(remoteFileName, file);
        }

        sftp.Disconnect();
    }
}

下载文件

代码语言:javascript
运行
复制
/// <summary>
/// This sample will download a file on the remote system to your local machine.
/// </summary>
public void DownloadFile()
{
    string host           = "";
    string username       = "";
    string password       = "";
    string localFileName  = System.IO.Path.GetFileName(localFile);
    string remoteFileName = "";

    using (var sftp = new SftpClient(host, username, password))
    {
        sftp.Connect();

        using (var file = File.OpenWrite(localFileName))
        {
            sftp.DownloadFile(remoteFileName, file);
        }

        sftp.Disconnect();
    }
}

---------------------------------------------------------

2)另一个替代库是 WinSCP

---------------------------------------------------------

在下面的例子中:

代码语言:javascript
运行
复制
using System;
using WinSCP;

class Example
{
    public static int Main()
    {
        try
        {
            // Setup session options
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "example.com",
                UserName = "user",
                Password = "mypassword",
                SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
            };

            using (Session session = new Session())
            {
                // Connect
                session.Open(sessionOptions);

                // Upload files
                TransferOptions transferOptions = new TransferOptions();
                transferOptions.TransferMode = TransferMode.Binary;

                TransferOperationResult transferResult;
                transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions);

                // Throw on any error
                transferResult.Check();

                // Print results
                foreach (TransferEventArgs transfer in transferResult.Transfers)
                {
                    Console.WriteLine("Upload of {0} succeeded", transfer.FileName);
                }
            }

            return 0;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: {0}", e);
            return 1;
        }
    }
}

在这里发现的更多在这里

票数 17
EN

Stack Overflow用户

发布于 2012-05-18 17:55:17

FTP可以单独使用.NET完成。但是,SFTP没有内置的类。我建议看一看WinSCP

票数 6
EN

Stack Overflow用户

发布于 2013-10-31 10:40:02

同意Tejs。我只想澄清:

FtpWebRequest with EnableSsl = true意味着它的ftps、显式模式,或者在Filezilla中:"FTPES在显式TLS/SSL上,默认端口21“。你可以用内置的.net工具来完成这个任务。

对于隐式FTP (在Filezilla的措辞"FTPS在隐式TLS/SSL上,默认端口990")中,您必须使用第三方(例如ftps.codeplex.com)。

对于sftp (在Filezilla中使用"SSH文件传输协议,默认端口22"),您还必须使用第三方(例如sshnet.codeplex.com)。

正如Joachim Isaksson所说,如果你不能使用第三方,你必须自己实现它。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10657377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档