如果可能的话,在 C# 中使用 FtpWebRequest 实现无需第三方 dll 的 FTP/SFTP

2024-04-22

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

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

凭证就像

  1. 主机名 = sftp.xyz.com
  2. 用户 ID = abc
  3. 密码=123

我能够使用 IP 地址实现 ftp,但无法使用凭据实现上述主机名的 sftp。

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

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

我观察了 filezilla,它将主机名从 sftp.xyz.com 更改为 sftp://sftp.xyz.com 在文本框和命令行中,它将用户 ID 更改为[电子邮件受保护] /cdn-cgi/l/email-protection

我在代码中做了同样的事情,但 sftp 没有成功。

请在这方面需要紧急帮助。提前致谢。

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

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("[email protected] /cdn-cgi/l/email-protection", "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;
    }
}

UPDATE:

如果使用BizTalk,您可以使用 SFTP 适配器 https://social.technet.microsoft.com/wiki/contents/articles/19781.biztalk-server-2013-how-to-use-sftp-adapter.aspx, 使用ESB 工具包 https://msdn.microsoft.com/en-us/biztalk/biztalk-esbtoolkit.aspx。它自 2010 年以来一直受到支持。人们想知道为什么它没有进入.Net Framework

  1. BizTalk Server 2013:以 ESB 工具包 SFTP 中创建自定义适配器提供程序为例 https://social.technet.microsoft.com/wiki/contents/articles/22035.biztalk-server-2013-creating-custom-adapter-provider-in-esb-toolkit-sftp-as-an-example.aspx
  2. BizTalk Server 2013:如何使用 SFTP 适配器 https://social.technet.microsoft.com/wiki/contents/articles/22035.biztalk-server-2013-creating-custom-adapter-provider-in-esb-toolkit-sftp-as-an-example.aspx
  3. MSDN 文档 https://learn.microsoft.com/en-us/previous-versions/azure/dn232420(v=azure.100)

--

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

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

1)一个值得尝试的好库是SSHNet https://github.com/sshnet/SSH.NET.

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

It has:

  1. 更多功能,包括内置流媒体支持。
  2. API 文档
  3. 更简单的 API 来进行编码

文档中的示例代码:

列出目录

/// <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);
        }
    }
}

上传文件

/// <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();
    }
}

下载文件

/// <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 https://winscp.net/eng/docs/library

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

用下面的例子:

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;
        }
    }
}

在这里找到 https://winscp.net/eng/docs/library#csharp更多这里 https://winscp.net/eng/docs/library_examples.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果可能的话,在 C# 中使用 FtpWebRequest 实现无需第三方 dll 的 FTP/SFTP 的相关文章

  • 嵌套接口:将 IDictionary> 转换为 IDictionary>?

    我认为投射一个相当简单IDictionary
  • 类模板参数推导 - clang 和 gcc 不同

    下面的代码使用 gcc 编译 但不使用 clang 编译 https godbolt org z ttqGuL template
  • 从Web API同步调用外部api

    我需要从我的 Web API 2 控制器调用外部 api 类似于此处的要求 使用 HttpClient 从 Web API 操作调用外部 HTTP 服务 https stackoverflow com questions 13222998
  • BitTorrent 追踪器宣布问题

    我花了一点业余时间编写 BitTorrent 客户端 主要是出于好奇 但部分是出于提高我的 C 技能的愿望 我一直在使用理论维基 http wiki theory org BitTorrentSpecification作为我的向导 我已经建
  • 用于登录 .NET 的堆栈跟踪

    我编写了一个 logger exceptionfactory 模块 它使用 System Diagnostics StackTrace 从调用方法及其声明类型中获取属性 但我注意到 如果我在 Visual Studio 之外以发布模式运行代
  • 在 Windows 窗体中保存带有 Alpha 通道的单色位图会保存不同(错误)的颜色

    在 C NET 2 0 Windows 窗体 Visual Studio Express 2010 中 我保存由相同颜色组成的图像 Bitmap bitmap new Bitmap width height PixelFormat Form
  • HTTPWebResponse 响应字符串被截断

    应用程序正在与 REST 服务通信 Fiddler 显示作为 Apps 响应传入的完整良好 XML 响应 该应用程序位于法属波利尼西亚 在新西兰也有一个相同的副本 因此主要嫌疑人似乎在编码 但我们已经检查过 但空手而归 查看流读取器的输出字
  • 将多个表映射到实体框架中的单个实体类

    我正在开发一个旧数据库 该数据库有 2 个具有 1 1 关系的表 目前 我为每个定义的表定义了一种类型 1Test 1Result 我想将这些特定的表合并到一个类中 当前的类型如下所示 public class Result public
  • 使用 Bearer Token 访问 IdentityServer4 上受保护的 API

    我试图寻找此问题的解决方案 但尚未找到正确的搜索文本 我的问题是 如何配置我的 IdentityServer 以便它也可以接受 授权带有 BearerTokens 的 Api 请求 我已经配置并运行了 IdentityServer4 我还在
  • 转发声明和包含

    在使用库时 无论是我自己的还是外部的 都有很多带有前向声明的类 根据情况 相同的类也包含在内 当我使用某个类时 我需要知道该类使用的某些对象是前向声明的还是 include d 原因是我想知道是否应该包含两个标题还是只包含一个标题 现在我知
  • 如何序列化/反序列化自定义数据集

    我有一个 winforms 应用程序 它使用强类型的自定义数据集来保存数据进行处理 它由数据库中的数据填充 我有一个用户控件 它接受任何自定义数据集并在数据网格中显示内容 这用于测试和调试 为了使控件可重用 我将自定义数据集视为普通的 Sy
  • 如何查看网络连接状态是否发生变化?

    我正在编写一个应用程序 用于检查计算机是否连接到某个特定网络 并为我们的用户带来一些魔力 该应用程序将在后台运行并执行检查是否用户请求 托盘中的菜单 我还希望应用程序能够自动检查用户是否从有线更改为无线 或者断开连接并连接到新网络 并执行魔
  • 链接器错误:已定义

    我尝试在 Microsoft Visual Studio 2012 中编译我的 Visual C 项目 使用 MFC 但出现以下错误 error LNK2005 void cdecl operator new unsigned int 2
  • 向现有 TCP 和 UDP 代码添加 SSL 支持?

    这是我的问题 现在我有一个 Linux 服务器应用程序 使用 C gcc 编写 它与 Windows C 客户端应用程序 Visual Studio 9 Qt 4 5 进行通信 是什么very在不完全破坏现有协议的情况下向双方添加 SSL
  • 如何将带有 IP 地址的连接字符串放入 web.config 文件中?

    我们当前在 web config 文件中使用以下连接字符串 add name DBConnectionString connectionString Data Source ourServer Initial Catalog ourDB P
  • C# 模拟VolumeMute按下

    我得到以下代码来模拟音量静音按键 DllImport coredll dll SetLastError true static extern void keybd event byte bVk byte bScan int dwFlags
  • 哪种 C 数据类型可以表示 40 位二进制数?

    我需要表示一个40位的二进制数 应该使用哪种 C 数据类型来处理这个问题 如果您使用的是 C99 或 C11 兼容编译器 则使用int least64 t以获得最大的兼容性 或者 如果您想要无符号类型 uint least64 t 这些都定
  • C# - OutOfMemoryException 在 JSON 文件上保存列表

    我正在尝试保存压力图的流数据 基本上我有一个压力矩阵定义为 double pressureMatrix new double e Data GetLength 0 e Data GetLength 1 基本上 我得到了其中之一pressur
  • Windows 和 Linux 上的线程

    我在互联网上看到过在 Windows 上使用 C 制作多线程应用程序的教程 以及在 Linux 上执行相同操作的其他教程 但不能同时用于两者 是否存在即使在 Linux 或 Windows 上编译也能工作的函数 您需要使用一个包含两者的实现
  • 如何防止用户控件表单在 C# 中处理键盘输入(箭头键)

    我的用户控件包含其他可以选择的控件 我想实现使用箭头键导航子控件的方法 问题是家长控制拦截箭头键并使用它来滚动其视图什么是我想避免的事情 我想自己解决控制内容的导航问题 我如何控制由箭头键引起的标准行为 提前致谢 MTH 这通常是通过重写

随机推荐