C# 如果可能,在C中使用FtpWebRequest实现无第三方dll的FTP/SFTP#
我正试图通过C#中的FtpWebRequest类实现ftp/sftp,但至今未成功 我不想使用任何第三方免费或付费的dll 凭据就像C# 如果可能,在C中使用FtpWebRequest实现无第三方dll的FTP/SFTP#,c#,.net,winforms,C#,.net,Winforms,我正试图通过C#中的FtpWebRequest类实现ftp/sftp,但至今未成功 我不想使用任何第三方免费或付费的dll 凭据就像 主机名=sftp.xyz.com userid=abc 密码=123 我能够用Ip地址实现ftp,但无法用凭据实现上述主机名的sftp 对于sftp,我已将FtpWebRequest类的EnableSsl属性启用为true,但出现错误无法连接到远程服务器 我可以使用相同的凭据和主机名连接Filezilla,但不能通过代码连接 我观察到filezilla,它将主机名
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;
}
}
FTP可以单独使用.NET完成。但是,SFTP没有内置类。我建议看一看。同意Tejs。我想澄清一下: FtpWebRequest with EnableSsl=true意味着它是ftps,显式模式,或者用Filezilla的措辞:“FTPES-通过显式TLS/SSL的FTP,默认端口21”。您可以使用内置的.net工具来实现这一点 对于隐式FTP(在Filezilla措辞中为“ftps-隐式TLS/SSL上的FTP,默认端口990”),您必须使用第三方(例如ftps.codeplex.com) 对于sftp(在Filezilla措辞中为“SSH文件传输协议,默认端口22”),您还必须使用第三方(例如sshnet.codeplex.com) 正如Joachim Isaksson所说,如果你不能使用第三方,你必须自己实现它。更新: 如果使用,请使用。自2010年以来,它一直得到支持。有人想知道为什么它没有进入
.Net框架
--
不幸的是,目前仅使用框架还需要做很多工作。放置sftp
协议前缀不足以使其正常工作
现在,也许将来,仍然没有内置的.Net Framework支持
---------------------------------------
1)一个值得尝试的好库是。
---------------------------------------
它有:
/// <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);
}
}
}
与.ftp和ssl是ftps,而不是sftp。sftp是一种基于ssh的完全不同的协议。据我所知,在.NET.thnks中没有任何基于ssh的协议,但我该怎么办?我已经给出了以sftp开头的主机名,filezilla还在连接时将sftp添加到主机名之前。请详细说明一些步骤或代码。嗨@JoachimIsaksson我基本上有两个主机名,一个是sftp.xyz.com,另一个是ftp.xyz.com我该怎么办。我怎样才能做到这一点呢。net@pan4321如果没有第三方库,sftp在.NET中是不可用的,所以如果您真的不想使用任何第三方代码,您必须自己实现它。否则,SharpSSH对我有效,但(大多数?)商业实现更稳定。现在有可用的。sftp.UploadFile的语法在这里不正确(参数顺序不正确)。这一要点对我使用SSH.NET有所帮助:
/// <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();
}
}
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;
}
}
}