How do you Login to FTP using C#?
问题:
回答1:
Here is a very nice FTP Client for C#
http://www.codeproject.com/KB/IP/ftplibrary.aspx
Snippett from Link
//Get the basic FtpWebRequest object with the
//common settings and security
private FtpWebRequest GetRequest(string URI)
{
//create request
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//Set the login details
result.Credentials = GetCredentials();
//Do not keep alive (stateless mode)
result.KeepAlive = false;
return result;
}
/// <summary>
/// Get the credentials from username/password
/// </summary>
private System.Net.ICredentials GetCredentials()
{
return new System.Net.NetworkCredential(Username, Password);
}
回答2:
Native FTP support in .NET is fiddly.
I suggest using the free edtFTPnet component - I have used this in enterprisey applications with no problems whatsoever.
http://www.enterprisedt.com/products/edtftpnet/overview.html
回答3:
var url = "ftp://server";
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(url);
request.Credentials = new NetworkCredential(username, password);
回答4:
Something like:
var ftp = System.Net.FtpWebRequest(some url);
ftp.Credentials = something;
I think... :)
回答5:
I'm just throwing my hat in the ring for anyone searching this topic. Here is how I did this recently. I made an FTPProvider class to handle the connection wiring and an FTPSettings class to keep everything modular. This first line below makes the connection and returns the FtpWebRequest you will need to do things like download, delete, and get lists from the FTP server. A complete list and examples can be found here on the msdn.
FtpWebRequest request = FTPProvider.GetFTPRequest(FTPProvider.Settings.FTPPath);
public class FTPProvider
{
public FTPSettings Settings { get; set; }
public FtpWebRequest ConnectToFtp(Uri ftpServerUri)
{
var request = (FtpWebRequest)WebRequest.CreateDefault(ftpServerUri);
request.Credentials = new NetworkCredential(Settings.User, Settings.Password);
return request;
}
public FtpWebRequest GetFTPRequest(string filepath)
{
var ftpServerUri = new Uri(filepath);
return ConnectToFtp(ftpServerUri);
}
}
public class FTPSettings
{
public string FTPPath;
public string User;
public string Password;
}