本文整理汇总了C#中Renci.SshNet.SftpClient.UploadFile方法的典型用法代码示例。如果您正苦于以下问题:C# SftpClient.UploadFile方法的具体用法?C# SftpClient.UploadFile怎么用?C# SftpClient.UploadFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Renci.SshNet.SftpClient
的用法示例。
在下文中一共展示了SftpClient.UploadFile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Uploadfiles
private void Uploadfiles(PasswordConnectionInfo connectionInfo, IEnumerable<AchFileEntity> achFilesToUpload)
{
using (var sftp = new SftpClient(connectionInfo))
{
try
{
sftp.Connect();
foreach (var achfile in achFilesToUpload)
{
using (var stream = new MemoryStream())
{
var fileName = achfile.Name + ".ach";
var writer = new StreamWriter(stream);
// writer.Write(achfile.AchFileBody);
writer.Flush();
stream.Position = 0;
sftp.UploadFile(stream, fileName);
this.Manager.ChangeAchFilesStatus(achfile, AchFileStatus.Uploaded);
this.Manager.UnLock(achfile);
}
}
}
finally
{
sftp.Disconnect();
}
}
}
示例2: sendSFTP
private void sendSFTP(string filePath, string fileName)
{
SftpClient sftp = new SftpClient("194.2.93.194", "userece", "AdminPOCNUC01");
sftp.Connect();
using (FileStream filestream = File.OpenRead(filePath))
{
sftp.UploadFile(filestream, "/"+fileName, null);
sftp.Disconnect();
}
}
示例3: CopyFileFromLocalToRemote
public static void CopyFileFromLocalToRemote(string host, string user, string password, string localPath, string remotePath)
{
using (SftpClient client = new SftpClient(host, user, password))
{
client.KeepAliveInterval = TimeSpan.FromSeconds(60);
client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
client.OperationTimeout = TimeSpan.FromMinutes(180);
client.Connect();
bool connected = client.IsConnected;
// RunCommand(host, user, password, "sudo chmod 777 -R " + remotePath);
FileInfo fi = new FileInfo(localPath);
client.UploadFile(fi.OpenRead(), remotePath + fi.Name, true);
client.Disconnect();
}
}
示例4: UploadFile
public bool UploadFile(string filePath)
{
ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
try
{
using (var sftp = new SftpClient(connectionInfo))
{
sftp.Connect();
using (var file = File.OpenRead(filePath))
{
if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
{
sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
}
sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
string filename = Path.GetFileName(filePath);
sftp.UploadFile(file, filename);
}
sftp.Disconnect();
}
}
catch (Renci.SshNet.Common.SshConnectionException)
{
Console.WriteLine("Cannot connect to the server.");
return false;
}
catch (System.Net.Sockets.SocketException)
{
Console.WriteLine("Unable to establish the socket.");
return false;
}
catch (Renci.SshNet.Common.SshAuthenticationException)
{
Console.WriteLine("Authentication of SSH session failed.");
return false;
}
return true;
}
示例5: beginCracking
public void beginCracking()
{
log("beginning cracking process..");
var connectionInfo = new PasswordConnectionInfo (xml.Config.host, xml.Config.port, "root", xml.Config.Password);
using (var sftp = new SftpClient(connectionInfo))
{
using (var ssh = new SshClient(connectionInfo))
{
PercentStatus("Establishing SSH connection", 5);
ssh.Connect();
PercentStatus("Establishing SFTP connection", 10);
sftp.Connect();
log("Cracking " + ipaInfo.AppName);
PercentStatus("Preparing IPA", 25);
String ipalocation = AppHelper.extractIPA(ipaInfo);
using (var file = File.OpenRead(ipalocation))
{
log("Uploading IPA to device..");
PercentStatus("Uploading IPA", 40);
sftp.UploadFile(file, "Upload.ipa");
}
log("Cracking! (This might take a while)");
PercentStatus("Cracking", 50);
String binaryLocation = ipaInfo.BinaryLocation.Replace("Payload/", "");
String TempDownloadBinary = Path.Combine(AppHelper.GetTemporaryDirectory(), "crackedBinary");
var crack = ssh.RunCommand("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
log("Clutch -i 'Upload.ipa' " + binaryLocation + " /tmp/crackedBinary");
log("cracking output: " + crack.Result);
using (var file = File.OpenWrite(TempDownloadBinary))
{
log("Downloading cracked binary..");
PercentStatus("Downloading cracked binary", 80);
try
{
sftp.DownloadFile("/tmp/crackedBinary", file);
}
catch (SftpPathNotFoundException e)
{
log("Could not find file, help!!!!!");
return;
}
}
PercentStatus("Repacking IPA", 90);
String repack = AppHelper.repack(ipaInfo, TempDownloadBinary);
PercentStatus("Done!", 100);
log("Cracking completed, file at " + repack);
}
}
}
示例6: UploadFileWithOpenConnection
public static void UploadFileWithOpenConnection(string localFileToUpload, string targetFile, SftpClient sftp)
{
var directory = FlatRedBall.IO.FileManager.GetDirectory(targetFile, FlatRedBall.IO.RelativeType.Relative);
CreateDirectoriesRecursively(directory, sftp);
using (var file = File.OpenRead(localFileToUpload))
{
sftp.UploadFile(file, targetFile, canOverride: true);
}
}
示例7: Execute
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
{
try
{
using (var sftp = new SftpClient(Host, Port, Username, Password))
{
sftp.Connect();
using (var file = File.OpenRead(SourcePath))
{
sftp.UploadFile(file, TargetPath);
}
return DTSExecResult.Success;
}
}
catch (Exception ex)
{
log.Write(string.Format("{0}.Execute", GetType().FullName), ex.ToString());
return DTSExecResult.Failure;
}
}
示例8: UploadFile
private void UploadFile(SftpClient client, string filePath, string destination)
{
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
Console.WriteLine("Uploading {0} ({1:N0} bytes)",
filePath, fileStream.Length);
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(filePath));
}
}
示例9: doUpload
void doUpload(object sender, Renci.SshNet.Common.ShellDataEventArgs e)
{
var line = Encoding.UTF8.GetString(e.Data);
var arr = line.Split(Environment.NewLine.ToCharArray()).Where(x => !string.IsNullOrEmpty(x)).ToList();
//拿到路径之后开始上传
var remoteBasePath = arr[1];
using (var sftp = new SftpClient(server,port, user, pwd))
{
sftp.Connect();
foreach (var file in fileList)
{
string uploadfn = file;
var fileName = Path.GetFileName(file);
sftp.ChangeDirectory(remoteBasePath);
using (var uplfileStream = System.IO.File.OpenRead(uploadfn))
{
sftp.UploadFile(uplfileStream, fileName, true);
}
showLine(string.Format(" file===>{0} uploaed", file));
}
sftp.Disconnect();
}
shellStream.DataReceived -= doUpload;
shellStream.DataReceived += ShellStream_DataReceived;
}
示例10: PushFileSFTP
private StdResult<NoType> PushFileSFTP(string localFilePath, string distantDirectory)
{
if (!distantDirectory.StartsWith("/"))
distantDirectory = string.Concat("/", distantDirectory);
string distantPath = string.Format("ftp://{0}{1}", Host, distantDirectory);
LogDelegate(string.Format("[FTP] Distant path: {0}", distantPath));
try
{
//new SftpClient(Host, 22, Login, Pwd)
using (var sftp = new SftpClient(new PasswordConnectionInfo(Host, 22, Login, Pwd)))
{
sftp.HostKeyReceived += sftp_HostKeyReceived;
sftp.Connect();
sftp.ChangeDirectory(distantDirectory);
FileInfo fi = new FileInfo(localFilePath);
string distantFullPath = string.Format("{0}{1}", distantDirectory, fi.Name);
LogDelegate(string.Format("[FTP] ConnectionInfo : sftp.ConnectionInfo.IsAuthenticated:{0}, distant directory: {1}, username:{2}, host:{3}, port:{4}, distantPath:{5}",
sftp.ConnectionInfo.IsAuthenticated,
distantDirectory,
sftp.ConnectionInfo.Username,
sftp.ConnectionInfo.Host,
sftp.ConnectionInfo.Port,
distantFullPath));
//var sftpFiles = sftp.ListDirectory(distantDirectory);
//FileStream local = File.OpenRead(localFilePath);
//sftp.UploadFile(sr.BaseStream, distantDirectory, null);
using (StreamReader sr = new StreamReader(localFilePath))
{
LogDelegate(string.Format("[FTP] File being sent : {0} bytes.", sr.BaseStream.Length));
sftp.UploadFile(sr.BaseStream, distantFullPath);
}
}
LogDelegate(string.Format("[FTP] File Sent successfully."));
return StdResult<NoType>.OkResult;
}
catch (Exception e)
{
if (LogDelegate != null)
{
Mailer mailer = new Mailer();
mailer.LogDelegate = LogDelegate;
Exception exception = e;
while (exception != null)
{
LogDelegate("[FTP] Exception envoi : " + exception.Message + " " + exception.StackTrace);
exception = e.InnerException;
}
string emailConf = ConfigurationManager.AppSettings["NotificationEmail"];
mailer.SendMail(emailConf, "[Canal Collecte] Erreur FTP!", exception.Message + "<br/>" + e.StackTrace, null, ConfigurationManager.AppSettings["NotificationEmail_CC"]);
}
return StdResult<NoType>.BadResultFormat("[FTP] Exception envoi: {0} /// {1}", e.Message);
}
}
示例11: btnFTP_Click
private void btnFTP_Click(object sender, EventArgs e)
{
//// Get the object used to communicate with the server.
//FtpWebRequest request = (FtpWebRequest)WebRequest.Create("sftp://ftp.s6.exacttarget.com");
//request.Method = WebRequestMethods.Ftp.UploadFile;
//// This example assumes the FTP site uses anonymous logon.
//request.Credentials = new NetworkCredential("6177443", "mD.5.d6T");
//// Copy the contents of the file to the request stream.
//StreamReader sourceStream = new StreamReader(@"D:\\DataExtension1List1.txt");
//byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
//sourceStream.Close();
//request.ContentLength = fileContents.Length;
//Stream requestStream = request.GetRequestStream();
//requestStream.Write(fileContents, 0, fileContents.Length);
//requestStream.Close();
//FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//MessageBox.Show(string.Format("Archivo Subido, Estado {0}", response.StatusDescription), "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
//response.Close();
const int port = 22;
const string host = "ftp.s6.exacttarget.com";
const string username = "6177443";
const string password = "mD.5.d6T";
const string workingdirectory = "/Import//";
const string uploadfile = @"D:\\DataExtension1List1.txt";
Console.WriteLine("Creating client and connecting");
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
Console.WriteLine("Connected to {0}", host);
client.ChangeDirectory(workingdirectory);
Console.WriteLine("Changed directory to {0}", workingdirectory);
//var listDirectory = client.ListDirectory(workingdirectory);
//Console.WriteLine("Listing directory:");
//foreach (var fi in listDirectory)
//{
// Console.WriteLine(" - " + fi.Name);
//}
using (var fileStream = new FileStream(uploadfile, FileMode.Open))
{
Console.WriteLine("Uploading {0} ({1:N0} bytes)",
uploadfile, fileStream.Length);
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(uploadfile));
}
MessageBox.Show("Archivo " + uploadfile + " subido a " + host, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
示例12: SendBySftp
private async Task SendBySftp(FtpMessage ftpMessage)
{
var host = ftpMessage.Configuration.FtpHost;
var path = ftpMessage.Filename;
var username = ftpMessage.Configuration.Username;
var password = ftpMessage.Configuration.Password;
var port = ftpMessage.Configuration.FtpPort;
using (var sftpClient = new SftpClient(host.Host, port, username, password))
{
sftpClient.Connect();
//sftpClient.ChangeDirectory("tmp");
var ms = new MemoryStream(ftpMessage.Data);
sftpClient.UploadFile(ms, path);
sftpClient.Disconnect();
}
}
示例13: Execute
private void Execute()
{
var keyPath = textBoxFile.Text;
var host = textBoxHost.Text;
var user = textBoxUser.Text;
var pass = textBoxPass.Text;
Action _execute = () =>
{
try
{
//Read Key
Status("opening key");
FileStream file = File.OpenRead(keyPath);
//Connect to SFTP
Status("sftp connecting");
SftpClient sftp = new SftpClient(host, user, pass);
sftp.Connect();
//users home directory
string homepath = "/home/" + user + "/";
if (user == "root")
{
homepath = "/root/";
}
//Find authorized keys
string authKeys = homepath + ".ssh/authorized_keys";
if (!sftp.Exists(authKeys))
{
Status("creating");
if (!sftp.Exists(homepath + ".ssh"))
sftp.CreateDirectory(homepath + ".ssh");
sftp.Create(authKeys);
}
//Download
Status("downloading");
Stream stream = new MemoryStream();
sftp.DownloadFile(authKeys, stream);
Status("downloaded");
//Read
byte[] buffer = new byte[10240]; //No key should be this large
int length = file.Read(buffer, 0, buffer.Length);
//Validate
String strKey;
if (length < 20)
{
Status("Invalid Key (Length)");
return;
}
if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' &&
buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' &&
buffer[6] == (byte) 'a')
{
strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim();
}
else
{
Status("Invalid Key (Format)");
return;
}
stream.Seek(0, SeekOrigin.Begin);
StreamReader reader = new StreamReader(stream);
//Check for key that might already exist
while (!reader.EndOfStream)
{
var line = reader.ReadLine().Trim();
if (line == strKey)
{
Status("key already exists");
return;
}
}
//Check new line
if (stream.Length != 0)
{
stream.Seek(0, SeekOrigin.End);
stream.WriteByte((byte) '\n');
}
else
{
stream.Seek(0, SeekOrigin.End);
}
//Append
Status("appending");
stream.Write(buffer, 0, length);
//Upload
Status("uploading");
stream.Seek(0, SeekOrigin.Begin);
sftp.UploadFile(stream, authKeys);
Status("done");
//.........这里部分代码省略.........
示例14: combineAdd
//.........这里部分代码省略.........
{
ad.ad_details[0].Images[0].ServerUrl = ImagePath;
ad.ad_details[0].Images[0].IsServerUploaded = true;
}
Old.ad_details.Add(ad.ad_details[0]);
}
ad.ad_details = Old.ad_details;
if (Old.publisherUrl.Contains(ad.publisherUrl[0])) ad.publisherUrl = Old.publisherUrl;
else
{
Old.publisherUrl.Add(ad.publisherUrl[0]);
ad.publisherUrl = Old.publisherUrl;
}
if (Old.advertiserUrl.Contains(ad.advertiserUrl[0])) ad.advertiserUrl = Old.advertiserUrl;
else
{
Old.advertiserUrl.Add(ad.advertiserUrl[0]);
ad.advertiserUrl = Old.advertiserUrl;
}
ad.Update(ad);
}
catch { }
}
else
{
// ad.publisherUrl = new List<string> { publisherUrl };
try
{
//int index = Old.ad_details.FindIndex(a => a.advertiserUrl == ad.advertiserUrl[0]);
string ImagePath = ad.Id + "_" + 0 + "_" + 0+".jpg";
if (UploadImage(ImagePath, ad.ad_details[0].Images[0].ImageUrl))
{ ad.ad_details[0].Images[0].ServerUrl = ImagePath;
ad.ad_details[0].Images[0].IsServerUploaded = true;
}
ad.Insert(ad);
}
catch { }
}
}
*/
internal static bool UploadImage(string FileName, string ImageUrl)
{
try
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadFile(new Uri(ImageUrl), FileName);
}
const int port = 22;
const string host = "66.85.92.2";
const string username = "root";
const string password = "fuckoff321";
const string workingdirectory = "/var/www/ad_images/";
// const string uploadfile = path;
Console.WriteLine("Creating client and connecting");
if (System.IO.File.Exists(FileName))
{
using (var client = new SftpClient(host, port, username, password))
{
client.Connect();
client.ChangeDirectory(workingdirectory);
//var listDirectory = client.ListDirectory(workingdirectory);
//foreach (var fi in listDirectory)
//{
// Console.WriteLine(" - " + fi.Name);
//}
using (var fileStream = new FileStream(FileName, FileMode.Open))
{
Console.WriteLine("Uploading {0} ({1:N0} bytes)",
FileName, fileStream.Length);
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(FileName));
}
try
{
System.IO.File.Delete(FileName);
}
catch (Exception ex)
{ }
return true;
}
}
return false;
}
catch { return false; }
}
示例15: UploadFile
public bool UploadFile(string localFileName, Action<ulong> uploadCallback, string remotePath = "")
{
string remoteFileName = remotePath+System.IO.Path.GetFileName(localFileName);
using (var sftp = new SftpClient(GenerateConnectionInfo()))
{
sftp.Connect();
//TODO: check if the directory exists!
sftp.ChangeDirectory(Workingdirectory);
sftp.ErrorOccurred += ssh_ErrorOccurred;
using (var file = File.OpenRead(localFileName))
{
try
{
sftp.UploadFile(file, remoteFileName, uploadCallback);
}
catch (Exception e)
{
return false;
}
}
sftp.Disconnect();
}
return true;
}