我需要创建一个C#应用程序,根据app.config文件中输入的设置(使用"ftp\ftps\sftp")将excel文件上传到"FTP/SFTP"服务器.
我很满意这些协议,有很多疑点.
代码如下:
string PureFileName = new FileInfo(fileName).Name;
string uploadUrl = String.Format("ftp://{0}/{1}", ftpurl, PureFileName);
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(uploadUrl);
req.Proxy = null;
req.Method = WebRequestMethods.Ftp.UploadFile;
req.Credentials = new NetworkCredential(user, pass);
req.UseBinary = true;
req.UsePassive = true;
byte[] data = File.ReadAllBytes(fileName);
req.ContentLength = data.Length;
Stream stream = req.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
FtpWebResponse res = (FtpWebResponse)req.GetResponse();
Run Code Online (Sandbox Code Playgroud)
是否喜欢url从FTP 更改为FTPS?
string uploadUrl = String.Format("ftps://{0}/{1}", ftpurl, PureFileName);
Run Code Online (Sandbox Code Playgroud)
如果您的代码能够处理FTPS,它通常也能够处理FTP,但是有很多代码只能处理FTP而不能处理FTPS.由于SFTP是一个完全不同的协议代码处理FTP/FTPS通常无法做SFTP.而SFTP处理代码不会做FTP/FTPS.有一些例外,即FileZilla可以在单个应用程序中处理所有这些协议.
至于使用FTP和FtpWebRequests,请参阅msdn.使用SFTP和FtpWebRequests是不可能的,但还有其他库.
该SFTP和FTP/FTPS是两个完全不同的协议.您无法使用FTP上传到SFTP服务器,反之亦然.FTPS是FTP over TLS/SSL会话.大多数FTP客户端/库也支持FTPS.
.NET框架(通过FtpWebRequest类)本身仅支持FTP(S ).要使用FTPS,请使用ftps://URL或设置FtpWebRequest.EnableSsl为true.
在.NET框架中,SFTP没有本机支持.您必须为SFTP使用第三方库.
有些库为所有这些协议提供统一的接口.
例如,使用WinSCP .NET程序集,它(几乎)只是设置SessionOptions.Protocol为Protocol.FTP或者Protocol.SFTP.
SFTP协议:
SessionOptions sessionOptions = new SessionOptions {
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
};
Session session = new Session();
session.Open(sessionOptions);
Run Code Online (Sandbox Code Playgroud)
FTP协议:
SessionOptions sessionOptions = new SessionOptions {
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
Session session = new Session();
session.Open(sessionOptions);
Run Code Online (Sandbox Code Playgroud)
FTPS协议:
SessionOptions sessionOptions = new SessionOptions {
Protocol = Protocol.Ftp,
FtpSecure = FtpSecure.Explicit,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
Session session = new Session();
session.Open(sessionOptions);
Run Code Online (Sandbox Code Playgroud)
如果您需要使会话可配置,则可以使用SessionOptions.ParseUrl允许您使用在配置文件中设置的单个连接字符串(URL)配置主要会话选项来轻松实现.
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.ParseUrl(connectionString);
Session session = new Session();
session.Open(sessionOptions);
Run Code Online (Sandbox Code Playgroud)
连接字符串可以是:
sftp://user@mypassword;fingerprint=ssh-rsa-xxxxxxxxxxx...=@example.comftp://user@mypassword@example.comftpes://user@mypassword@example.com您可以让WinSCP(GUI)为您生成URL(连接字符串).
请注意,WinSCP .NET程序集不是本机.NET库.它只是一个围绕控制台应用程序(WinSCP)的瘦.NET包装器.
可能存在支持具有统一接口的所有协议的本机.NET库.但我不知道有任何免费的.
(我是WinSCP的作者)
| 归档时间: |
|
| 查看次数: |
3003 次 |
| 最近记录: |