gpt4 book ai didi

c# - 如果可能,在 C# 中使用 FtpWebRequest 在没有第 3 方 dll 的情况下实现 FTP/SFTP

转载 作者:可可西里 更新时间:2023-11-01 08:05:33 28 4
gpt4 key购买 nike

我正在尝试通过 C# 中的 FtpWebRequest 类实现 ftp/sftp,但直到现在都没有成功。

我不想使用任何第 3 方免费或付费 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在文本框和命令行中,它将用户标识更改为 abc@sftp.xyz.com

我在代码中做了同样的事情,但对 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("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;
}
}

最佳答案

更新:

如果使用 BizTalk, you can work with the SFTP Adapter , 使用 ESB Toolkit .它自 2010 年以来一直受到支持。有人想知道为什么它没有进入 .Net Framework

  1. BizTalk Server 2013: Creating Custom Adapter Provider in ESB Toolkit SFTP As an Example
  2. BizTalk Server 2013: How to use SFTP Adapter
  3. MSDN Docs

--

不幸的是,目前仅使用框架仍需要大量工作。放置 sftp 协议(protocol)前缀不足以使其工作 现在仍然没有内置的 .Net Framework 支持,也许在未来。

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

1) 一个值得尝试的好库是 SSHNet .

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

它有:

  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

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

以下面的例子:

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

Found heremore here .

关于c# - 如果可能,在 C# 中使用 FtpWebRequest 在没有第 3 方 dll 的情况下实现 FTP/SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10657377/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com