//public string SendFTPImagem(string host, string username, string password, string lista_imagens, string nmCampanha) //{ // EMailMarketingBLL result = new EMailMarketingBLL(); // using (var sftp = new SftpClient(host, username, password)) // { // sftp.Connect(); // string nmCampanha_aux = nmCampanha; // int cont = 1; // while (sftp.Exists(nmCampanha_aux)) // { // nmCampanha_aux = nmCampanha + "_" + cont; // cont++; // } // nmCampanha = nmCampanha_aux; // if (!sftp.Exists(nmCampanha)) // { // sftp.CreateDirectory(nmCampanha); // } // sftp.ChangeDirectory(nmCampanha); // using (var fileStream = new FileStream(lista_imagens, FileMode.Open)) // { // sftp.BufferSize = 4 * 1024; // bypass Payload error large files // sftp.UploadFile(fileStream, Path.GetFileName(lista_imagens)); // } // sftp.Disconnect(); // } // return result.ToString(); //} public string ContCamp(string host, string username, string password, string nmCampanha) { using (var sftp = new SftpClient(host, username, password)) { sftp.Connect(); string nmCampanha_aux = nmCampanha; int cont = 1; while (sftp.Exists(nmCampanha_aux)) { nmCampanha_aux = nmCampanha + "_" + cont; cont++; } nmCampanha = nmCampanha_aux; if (!sftp.Exists(nmCampanha)) { sftp.CreateDirectory(nmCampanha); } sftp.Disconnect(); } return(nmCampanha); }
// Move file at the ftp private static bool RemoteMove(SftpClient sftp, string Source, string Target) { string _stage = ""; try { // _stage = "Checkings"; if (!sftp.Exists(Source)) { throw new Exception("Source file not found."); } if (sftp.Exists(Target)) { throw new Exception("Target file already exists."); } // _stage = "Moving remote file"; sftp.RenameFile(Source, Target); } catch (Exception ex) { Console.WriteLine($"[{_stage}] {ex.Message}"); return(false); } // OK return(true); }
/// <summary> /// Delete a test folder on a server /// </summary> /// <param name="serverName">The server to connect to</param> /// <param name="userName">The user to log into</param> /// <param name="password">The password of the user</param> /// <param name="folderName">The name of the test folder to delete</param> public static void DeleteFiles(string serverName, string userName, string password, string folderName) { using (SftpClient client = new SftpClient("serverName", userName, password)) { client.Connect(); // cd TestDir if (!client.Exists("TestDir")) { return; } client.ChangeDirectory("TestDir"); // Delete folder if (!string.IsNullOrWhiteSpace(folderName) && client.Exists(folderName)) { // client.DeleteDirectory is not recursive, so have to go in and delete every file first Parallel.ForEach(client.ListDirectory(folderName), k => { try { client.DeleteFile(k.FullName); } // Catch delete failures coming from trying to delete './' or '../' catch (SshException) { } }); client.DeleteDirectory(folderName); } client.Disconnect(); } }
private bool CreateRemoteDirectory(string remote_dir_path) { if (!IsConnected) { return(false); } string _path = "/"; try { string[] split = remote_dir_path.Split('/'); for (int i = 0; i < split.Length; i++) { _path += split[i] + "/"; if (!sftp.Exists(_path)) { //string com = "mkdir '" + _path + "'"; ////SendCommand(com); //ssh.RunCommand(com); sftp.CreateDirectory(_path); } } return(true); } catch (Exception ex) { Log.PrintError(ex.Message + "/ path = " + _path, "Classes.SSHManager.CreateRemoteDirectory"); Log.ErrorIntoUI(ex.Message + "/ path = " + _path, "CreateRemoteDirectory", Status.current.richTextBox_status); WindowMain.current.ShowMessageDialog("Create Directory", "Fail : " + ex.Message, MahApps.Metro.Controls.Dialogs.MessageDialogStyle.Affirmative); return(false); } }
public void UploadFolder(string folder) { Logger.Instance.Info("Uploading folder: {0}", folder); //create folder var remoteFolder = Path.GetFileName(folder); if (_client.Exists(remoteFolder)) { throw new Exception("Folder exists in remote"); } _client.CreateDirectory(remoteFolder); _client.ChangeDirectory(remoteFolder); foreach (var file in Directory.GetFiles(folder, "*", SearchOption.TopDirectoryOnly)) { this.UploadFile(file); } //sub folders foreach (var subFolder in Directory.GetDirectories(folder)) { this.UploadFolder(subFolder); } _client.ChangeDirectory("../"); }
private void CreateDirectory(SftpClient client, string destination) { var paths = destination.TrimEnd('/').Split("/"); if (paths[0]?.Length == 0) { paths[0] = "/"; } var currentPath = paths[0]; if (!client.Exists(currentPath)) { _logger.LogInformation("Create directory {0}", currentPath); client.CreateDirectory(currentPath); } foreach (var item in paths.Skip(1)) { currentPath = Path.Combine(currentPath, item); if (!client.Exists(currentPath)) { _logger.LogInformation("Create directory {0}", currentPath); client.CreateDirectory(currentPath); } } }
public void CreateChallengeFile(string filename, string contents) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("Must not be null or empty!", nameof(filename)); } if (string.IsNullOrEmpty(contents)) { throw new ArgumentException("Must not be null or empty!", nameof(contents)); } using (SftpClient client = _sftpClientFactory.CreateClient()) { if (!client.Exists(".well-known/acme-challenge")) { if (!client.Exists(".well-known")) { client.CreateDirectory(".well-known"); } client.CreateDirectory(".well-known/acme-challenge"); } client.ChangeDirectory(".well-known/acme-challenge"); client.WriteAllText(string.Concat(client.WorkingDirectory, "/", filename), contents); } _logger.LogInformation("Challenge presented."); }
private void TransferPrereqs(SshClient sshClient, ServerDistro distro) { string prereqsPath = (distro == ServerDistro.RPM) ? rpmPackages : debianPackages; using (var sftpClient = new SftpClient(sshClient.ConnectionInfo)) { sftpClient.Connect(); List <string> files = ListPrereqsFiles(prereqsPath); foreach (string file in files) { using (var fileStream = new FileStream(file, FileMode.Open)) { Console.WriteLine("Uploading {0} ({1:N0} bytes)", file, fileStream.Length); sftpClient.BufferSize = 4 * 1024; // bypass Payload error large files string path = file.Remove(file.IndexOf(Path.GetFileName(file))).Replace(@"\", "/"); string filename = Path.GetFileName(file); string[] dirs = path.TrimEnd('/').Split('/'); foreach (var dir in dirs) { try { if (!sftpClient.Exists(dir)) { sftpClient.CreateDirectory(dir); } sftpClient.ChangeDirectory(dir); } catch { //Log: Directory already exists } } if (sftpClient.Exists(filename)) { sftpClient.UploadFile(fileStream, filename); } sftpClient.ChangePermissions(filename, 755); sftpClient.ChangeDirectory("/home/" + sshClient.ConnectionInfo.Username); } } } ////chmod +x for the file to be executable //var cmd = sshClient.CreateCommand("chmod +x ./" + Path.GetFileName(agentPath)); //var result = cmd.BeginExecute(); //using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true)) //{ // while (!result.IsCompleted || !reader.EndOfStream) // { // string line = reader.ReadLine(); // if (line != null) // { // //Log: result // } // } //} //cmd.EndExecute(result); }
void UploadData(PatientEntity model, ObservableCollection <PatientReport> reports) { //try //{ APIResult result = new APIResult(); if (model.PatientId == 0) { result = SyncPatientDetails(model, reports, false); } else { result = SyncPatientDetails(model, reports, true); } if (result.status == "ok") { foreach (var item in reports) { item.Sync = true; new Patient().UpdateSyncStatus(item.Id); } } string localPath = Path.Combine(Program.BaseDir(), "Uploads", model.UniqueID.ToString()); string ftpHost = ConfigurationManager.AppSettings["ftpHost"].ToString(); string ftpUserName = ConfigurationManager.AppSettings["ftpUserName"].ToString(); string ftpPassword = ConfigurationManager.AppSettings["ftpPassword"].ToString(); using (var client = new SftpClient(ftpHost, ftpUserName, ftpPassword)) { client.Connect(); client.ChangeDirectory("/home/ftpuser11/ftp/files"); string rootDir = client.WorkingDirectory + "/" + model.UniqueID.ToString(); if (!client.Exists(rootDir)) { client.CreateDirectory(rootDir); } foreach (var item in PatientReports) { string rootDataDir = rootDir + "/" + item.UniqueID.ToString(); if (!client.Exists(rootDataDir)) { client.CreateDirectory(rootDataDir); client.ChangeDirectory(rootDataDir); UploadDirectory(client, localPath, rootDir); } } client.Disconnect(); } //} //catch (Exception ex) //{ // ModernDialog.ShowMessage("An error has occurred on the server", "Alert", MessageBoxButton.OK); // throw ex; //} }
bool IFtpSession.DirectoryExists(string path) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentNullException(nameof(path)); } return(_sftpClient.Exists(path) && ((IFtpSession)this).GetObjectType(path) == FtpObjectType.Directory); }
public Task <bool> ExistsAsync(string path) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } EnsureClientConnected(); return(Task.FromResult(_client.Exists(NormalizePath(path)))); }
/// <summary> /// Check file path or directory exists /// </summary> /// <returns>exists or not</returns> public bool IsPathExists(string path) { bool ret = false; if (sftpClient != null && sftpClient.IsConnected) { ret = sftpClient.Exists(path); } return(ret); }
//サーバー上のテキストファイルの内容をStreamReaderとして出力します public StreamReader GetFileRead(string From_File, bool IsErrorLogMode = false) { if (!IsConnected) { return(new StreamReader(new MemoryStream())); } else if (SFTP_Server != null && !SFTP_Server.IsConnected) { SFTP_Server.Connect(); } try { if (SFTP_Server.Exists(From_File)) { return(SFTP_Server.OpenText(From_File)); } else { return(new StreamReader(new MemoryStream())); } } catch (Exception e) { if (IsErrorLogMode) { Sub_Code.Error_Log_Write(e.Message); } return(new StreamReader(new MemoryStream())); } }
public Task <bool> IsDirectoryExists(string directoryPath) { return(HandleCommonExceptions(() => { if (_client.Exists(directoryPath)) { var file = _client.Get(directoryPath); return file.IsDirectory; } return false; })); }
public string GetDirectoryContent() { if (password == null || password.Length < 1) { if (debug) { Debug.LogError("sftpaccess >> No Password specified!"); } return(null); } using (var client = new SftpClient(host, username, password)) { client.Connect(); if (debug) { Debug.Log("Is connected? " + client.IsConnected); } string baseReadWriteDir = "/surveylog/"; string playerName = PlayerPrefs.GetString("name"); //check if /$name exists, if not create it, then switch the workdir client.ChangeDirectory(baseReadWriteDir); if (!client.Exists(playerName)) { client.CreateDirectory(playerName); } client.ChangeDirectory(playerName); //check if /$name/$type exists, if not create it, then switch the workdir if (!client.Exists(gameTypeString)) { client.CreateDirectory(gameTypeString); } client.ChangeDirectory(gameTypeString); Console.WriteLine("Changed directory to {0}", baseReadWriteDir); // no. of files currently List <SftpFile> files = client.ListDirectory(client.WorkingDirectory).ToList(); client.Disconnect(); String ret = ""; foreach (var item in files) { if (debug) { Debug.Log(">>" + item); } if (!item.Name.StartsWith(".")) { ret += "> " + item.Name + "\r\n"; } } return(ret); } }
private static void BackupIfExists(string targetFile, SftpClient client) { if (client.Exists(targetFile)) { var backupName = targetFile + ".old"; var i = 2; while (client.Exists(backupName)) { backupName = targetFile + ".old" + i; i++; } client.RenameFile(targetFile, backupName); } }
private void UploadDirectory(SftpClient client, string localPath, string remotePath, Action <ulong> uploadCallback) { Log.Information($@"Uploading directory {localPath} to {remotePath}"); IEnumerable <FileSystemInfo> infos = new DirectoryInfo(localPath).EnumerateFileSystemInfos(); foreach (FileSystemInfo info in infos) { if (info.Attributes.HasFlag(FileAttributes.Directory)) { string subPath = remotePath + @"/" + info.Name; if (!client.Exists(subPath)) { client.CreateDirectory(subPath); } UploadDirectory(client, info.FullName, remotePath + @"/" + info.Name, uploadCallback); } else { using (Stream fileStream = new FileStream(info.FullName, FileMode.Open)) { Debug.WriteLine( @"Uploading {0} ({1:N0} bytes)", info.FullName, ((FileInfo)info).Length); client.UploadFile(fileStream, remotePath + @"/" + info.Name, uploadCallback); } } } }
/// <summary> /// Creates the linux directory recursively. /// </summary> /// <param name="client">The client.</param> /// <param name="path">The path.</param> /// <exception cref="ArgumentException">Argument path must start with + LinuxDirectorySeparator.</exception> private static void CreateLinuxDirectoryRecursive(SftpClient client, string path) { if (path.StartsWith(LinuxDirectorySeparator) == false) { throw new ArgumentException("Argument path must start with " + LinuxDirectorySeparator); } if (client.Exists(path)) { var info = client.GetAttributes(path); if (info.IsDirectory) { return; } } var pathParts = path.Split(new[] { LinuxDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); pathParts = pathParts.Skip(0).Take(pathParts.Length - 1).ToArray(); var priorPath = LinuxDirectorySeparator + string.Join(LinuxDirectorySeparator, pathParts); if (pathParts.Length > 1) { CreateLinuxDirectoryRecursive(client, priorPath); } client.CreateDirectory(path); }
public void UploadFolder(string localPath, string remotePath) { Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath); var infos = new DirectoryInfo(localPath).EnumerateFileSystemInfos(); foreach (var info in infos) { if (info.Attributes.HasFlag(FileAttributes.Directory)) { var subPath = remotePath + "/" + info.Name; if (!client.Exists(subPath)) { client.CreateDirectory(subPath); } UploadFolder(info.FullName, remotePath + "/" + info.Name); } else { using (Stream fileStream = new FileStream(info.FullName, FileMode.Open)) { Console.WriteLine( "Uploading {0} ({1:N0} bytes)", info.FullName, ((FileInfo)info).Length); client.UploadFile(fileStream, remotePath + "/" + info.Name); } } } }
public PersistBackup GetBackup(string server, string backupName) { var servers = _config.GetSection("Servers"); var entry = servers.GetSection(server); if (entry == null) { return(null); } PersistBackup backup = null; var hostName = entry.Key; var password = entry.Value; using (var client = new SftpClient(hostName, "arma3-public", password)) { client.Connect(); if (client.Exists(filePath)) { var mem = new MemoryStream(); client.DownloadFile(filePath, mem); mem.Position = 0; backup = PersistBackup.Read(mem, client.GetLastWriteTime(filePath), hostName).FirstOrDefault(b => b.Name == backupName); } client.Disconnect(); } return(backup); }
static void UploadToSftp(string zipPath) { var connectionInfo = new ConnectionInfo("sftp.company.com", "SftpUser", new PasswordAuthenticationMethod("SftpUser", "SftpPassword"), new PrivateKeyAuthenticationMethod("rsa.key")); using (var sftpClient = new SftpClient(connectionInfo)) { sftpClient.Connect(); using (var stream = new FileStream(zipPath, FileMode.Open, FileAccess.Read)) { var directory = "\\TopLevelFolder\\Data"; if (sftpClient.Exists(directory) == false) { sftpClient.CreateDirectory(directory); } var fileName = Path.Combine(directory, Path.GetFileName(zipPath)); var previousValue = (double)0; sftpClient.UploadFile(stream, fileName, (value) => { WriteProgress(value, stream.Length, ref previousValue); }); } } }
private void UploadDirectory(SftpClient client, string localPath, string remotePath) { IEnumerable <FileSystemInfo> localFiles = new DirectoryInfo(localPath).EnumerateFileSystemInfos(); IEnumerable <SftpFile> remoteFiles = client.ListDirectory(remotePath); foreach (FileSystemInfo localFile in localFiles) { if (localFile.Attributes.HasFlag(FileAttributes.Directory)) { string subPath = remotePath + "/" + localFile.Name; if (!client.Exists(subPath)) { client.CreateDirectory(subPath); } UploadDirectory(client, localFile.FullName, remotePath + "/" + localFile.Name); } else { SftpFile remoteFile = remoteFiles.FirstOrDefault(f => f.Name == localFile.Name); if (remoteFile == null || localFile.LastWriteTimeUtc > remoteFile.LastWriteTimeUtc || ((FileInfo)localFile).Length != remoteFile.Attributes.Size) { using Stream fileStream = new FileStream(localFile.FullName, FileMode.Open); string processName = remoteFile == null ? "Adding" : "Updating"; Console.WriteLine($"{processName} {Path.GetRelativePath(projectFolder, localFile.FullName)}"); client.UploadFile(fileStream, $"{remotePath}/{localFile.Name}"); } } } }
private void SendExecutionLogs(string sessionId, string path) { //"btf-preprod-artifacts.psr.rd.hpicorp.net" string userName = "******"; string password = "******"; //get the log data TraceFactory.Logger.Debug($"Collecting logs for Session: {sessionId}"); var logData = SessionClient.Instance.GetLogData(sessionId); //we know on STB machines the log file will be present in the location of the calling assembly read that up and return the string if (string.IsNullOrEmpty(logData)) { logData = GetLogData(sessionId); } TraceFactory.Logger.Debug($"Uploading logs to Artifact server: {_btfArtifactsServerName}"); var connectionInfo = new ConnectionInfo(_btfArtifactsServerName, 22, userName, new PasswordAuthenticationMethod(userName, password)); using (var client = new SftpClient(connectionInfo)) { client.Connect(); if (!client.Exists(path)) { CreateDirectoryRecursively(client, path); } client.ChangeDirectory(path); client.WriteAllText($"{path}/{sessionId}.log", logData); } TraceFactory.Logger.Debug($"Log written: {path}/{sessionId}.log"); }
public override void PushFile(FileInfo file, Sheet sheet, FileImportMode mode = FileImportMode.Copy, bool _override = false) { switch (mode) { case FileImportMode.Copy: push(file, sheet); break; case FileImportMode.Move: push(file, sheet); file.Delete(); break; } void push(FileInfo file, Sheet sheet) { var fs = new System.IO.FileStream(file.FullName, FileMode.Open); using (var client = new SftpClient(new PasswordConnectionInfo(Server, Int32.Parse(Port), Username, Password))) { client.Connect(); if (!client.Exists(Path + "/" + sheet.Part.PartID)) { client.CreateDirectory(Path + "/" + sheet.Part.PartID); } client.UploadFile(fs, Path + "/" + sheet.Part.PartID + "/" + sheet.SheetID + ".pdf"); } } }
/// <summary> /// 파일명 지정해서 download /// </summary> /// <param name="remoteFileName"></param> public void DownloadFile(string remoteFileName, string localdir) { string host = @"13.209.113.71"; string username = "******"; pathLocalGet = localdir; if (!Directory.Exists(pathLocalGet)) { Directory.CreateDirectory(pathLocalGet); } string pathRemote = "/ftp/bnk_b/downloads/"; string pathRemoteSendDone = "/ftp/bnk_b/downloads/send_done/"; string pathRemoteFile = Path.Combine(pathRemote, remoteFileName); string pathRemoteSendDoneFile = Path.Combine(pathRemoteSendDone, remoteFileName); string pathLocalFile = Path.Combine(pathLocalGet, remoteFileName); PrivateKeyFile keyFile = new PrivateKeyFile(@"./bnk_sftp.pem"); var keyFiles = new[] { keyFile }; var methods = new List <AuthenticationMethod>(); methods.Add(new PrivateKeyAuthenticationMethod(username, keyFiles)); ConnectionInfo con = new ConnectionInfo(host, 10021, username, methods.ToArray()); using (SftpClient sftp = new SftpClient(con)) { try { sftp.Connect(); if (sftp.Exists(pathRemoteFile)) { File.Delete(pathLocalFile); using (Stream fileStream = File.OpenWrite(pathLocalFile)) { Console.WriteLine("Downloading {0}", pathRemoteFile); sftp.DownloadFile(pathRemoteFile, fileStream); sftp.RenameFile(pathRemoteFile, BuildRemoteSendDoneFileName(pathRemoteSendDoneFile)); } } else { Console.WriteLine("File not found skip {0}", pathRemoteFile); } sftp.Disconnect(); } catch (Exception er) { Console.WriteLine("An exception has been caught " + er.ToString()); } } }
public async Task EnsureDirectoryExists(SftpClient sftp, string path, CancellationToken ct) { logger.LogDebug("Ensuring directory exists", path); var dir = ""; foreach (string segment in path.Split('/')) { if (string.IsNullOrEmpty(segment)) { continue; } dir += "/" + segment; // Ignoring leading/ending/multiple slashes if (string.IsNullOrWhiteSpace(dir)) { continue; } var dirExists = await Task.Run(() => sftp.Exists(dir), ct); if (!dirExists) { logger.LogDebug("Creating dir", dir); await Task.Run(() => sftp.CreateDirectory(dir), ct); } } }
/// <summary> /// Deletes the directory recursively. /// </summary> /// <param name="remoteDirectory">The remote directory.</param> public static void DeleteDirectoryRecursive(string remoteDirectory, SftpClient Client) { if (!Client.Exists(remoteDirectory)) { return; } foreach (var file in Client.ListDirectory(remoteDirectory)) { if (file.Name.Equals(".") || file.Name.Equals("..")) { continue; } if (file.IsDirectory) { DeleteDirectoryRecursive(file.FullName, Client); } else { Client.DeleteFile(file.FullName); } } Client.DeleteDirectory(remoteDirectory); }
public HResult StartDirectoryEnumerationCallback(int commandId, Guid enumerationId, string relativePath, uint triggeringProcessId, string triggeringProcessImageFileName) { if (_activeEnumerations.ContainsKey(enumerationId)) { return(HResult.InternalError); } if (!sftpClient.Exists(GetFullPath(relativePath))) { return(HResult.PathNotFound); } var fileEnumerator = sftpClient.ListDirectory(GetFullPath(relativePath)).OrderBy(s => Path.GetFileName(s.FullName)).ToList().GetEnumerator(); _activeEnumerations.TryAdd(enumerationId, fileEnumerator); return(HResult.Ok); }
private void DeleteDirectory(SftpClient sftpClient, string path) { if (!sftpClient.Exists(path)) { return; } foreach (var item in sftpClient.ListDirectory(path)) { if (".".Equals(item.Name) || "..".Equals(item.Name)) { continue; } if (item.IsDirectory) { DeleteDirectory(sftpClient, item.FullName); } else { sftpClient.Delete(item.FullName); } } sftpClient.Delete(path); }
private void DeleteDirectory(SftpClient Sftp, string Path) { try { if (Sftp.Exists(Path)) { foreach (SftpFile File in Sftp.ListDirectory(Path)) { if ((File.Name != ".") && (File.Name != "..")) { if (File.IsDirectory) { DeleteDirectory(Sftp, File.FullName); } else { Sftp.DeleteFile(File.FullName); } } } Sftp.DeleteDirectory(Path); } } catch (Exception e) { Logger.Error(string.Format("Delete directory {0} threw an exception. Ex: {1}", Path, e.Message)); } }
public void ExistsTest() { ConnectionInfo connectionInfo = null; // TODO: Initialize to an appropriate value SftpClient target = new SftpClient(connectionInfo); // TODO: Initialize to an appropriate value string path = string.Empty; // TODO: Initialize to an appropriate value bool expected = false; // TODO: Initialize to an appropriate value bool actual; actual = target.Exists(path); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
private static void CreatSSHDir(SftpClient ssh, string file) { var newDir = Tools.Misc.GetUnixDirecoryOfFile(file); if (ssh.Exists(newDir)) return; string[] dirs = new string[newDir.ToCharArray().Count(x => x == '/')]; dirs[0] = newDir; for (int i = 1; i < dirs.Count(); i++) { dirs[i] = Tools.Misc.GetUnixDirecoryOfFile(dirs[i - 1]); } for (int i = dirs.Count()-1; i >= 0; i--) { if (ssh.Exists(dirs[i])) continue; ssh.CreateDirectory(dirs[i]); } }