To easy up the work, I'm using SSH.NET Library to assist with the uploading process. Before start using the private key file you must convert it to a supported format by SSH.NET. For that, I'm using PuTTygen.
<appSettings>
<add key="FTPUploadPath" value="/mypath/ftpUploadPath"/>
<add key="FTPDownloadPath" value="/mypath/localpath"/>
<add key="FTPHost" value="host"/>
<add key="FTPPort" value="port"/>
<add key="FTPUserName" value="userName"/>
<add key="FTPPass" value="Password"/>
<!--private key file must be converted into a valid format using PuTTygen-->
<add key="PrivateKeyFile" value="\\mypath\WinSCP\SFX_PuTTygen.ppk"/>
</appSettings>
public static void FtpUploadFileUsingPrivateKeyFile(string ftpUploadPath, string localPath, string host, int port, string userName, string password)
{
var keyFile = new PrivateKeyFile(@ConfigHelper.PrivateKeyFile, password);
var keyFiles = new[] { keyFile };
var methods = new List<AuthenticationMethod>();
methods.Add(new PasswordAuthenticationMethod(userName, password));
methods.Add(new PrivateKeyAuthenticationMethod(userName, keyFiles));
var con = new ConnectionInfo(host, port, userName, methods.ToArray());
using (var client = new SftpClient(con))
{
client.Connect();
FileInfo f = new FileInfo(localPath);
string uploadfile = f.FullName;
if (client.IsConnected)
{
Console.WriteLine("Connected to FTP. Transferring File " + f.FullName);
}
var fileStream = new FileStream(uploadfile, FileMode.Open);
if (fileStream != null)
{
Console.WriteLine("YOU ARE NOT NULL");
}
client.BufferSize = 4 * 1024;
client.UploadFile(fileStream, ftpUploadPath + "/" + f.Name, null); //ConfigHelper.FTPUploadPath
client.Disconnect();
client.Dispose();
}
}
No comments:
Write comments