public bool Rename(IFileSystemItem item, string newName, bool overwrite = false) { FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip; string currentPath = item.GetUri().AbsolutePath; try { if (item.IsDirectory()) { string upperPath = IO.Path.GetFullPath(IO.Path.Combine(currentPath, "..")); string destUri = IO.Path.GetFullPath(IO.Path.Combine(upperPath, newName)); return(client.MoveDirectory(currentPath, destUri, exists)); } else { string destUri = IO.Path.GetFullPath(IO.Path.Combine(currentPath, newName)); return(client.MoveFile(item.GetUri().AbsoluteUri, destUri, exists)); } } catch (Exception e) { ExceptionHandler.LogException(e); } return(false); }
/// <summary> /// Attempt to upload multiple files to the FtpClient. /// </summary> /// <returns>DftpResultType.Ok, if the files are uploaded.</returns> public override DFtpResult Run() { //if remote source exists. if (multiFiles == null) { return(new DFtpResult(DFtpResultType.Error, "please select some files from local directory.")); } int numberOfFiles = multiFiles.Count; FtpExists existsMode = overwrite ? FtpExists.Overwrite : FtpExists.Skip; bool createDirectoryStructure = true; FtpVerify verifyMode = FtpVerify.Retry; ftpClient.RetryAttempts = 3; try { for (int i = 0; i < numberOfFiles; ++i) { String remoteTarget = remoteDirectory + (this.isWindows() ? "\\" : "/") + multiFiles[i].GetName(); ftpClient.UploadFile(multiFiles[i].GetFullPath(), remoteTarget, existsMode, createDirectoryStructure, verifyMode); } return(new DFtpResult(DFtpResultType.Ok, "Files are uploaded to remote directory.")); } catch (Exception ex) { return(new DFtpResult(DFtpResultType.Error, ex.Message)); } }
public bool AddItem(IFileSystemItem item, Directory directory, bool overwrite) { try { FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip; if (item.IsDirectory()) { client.CreateDirectory(IO.Path.Combine(directory.GetUri().AbsolutePath, item.Name)); List <IO.FileInfo> fileInfos = new List <IO.FileInfo>(); foreach (IFileSystemItem subitem in (item as Directory).EnumerateChildren()) { fileInfos.Add(subitem.FileInfo); } int uploaded = client.UploadFiles( fileInfos, directory.GetUri().AbsolutePath, exists, createRemoteDir: true); return(uploaded == fileInfos.Count); } else { return(AddFile(item as File, directory, overwrite)); } } catch (Exception e) { ExceptionHandler.LogException(e); } return(false); }
public override DFtpResult Run() { String source = localSelection.GetFullPath(); String target = remoteDirectory; if (target == "/") { target += localSelection.GetName(); } else { target += "/" + localSelection.GetName(); } FtpExists existsMode = overwrite ? FtpExists.Overwrite : FtpExists.Skip; bool createDirectoryStructure = true; FtpVerify verifyMode = FtpVerify.Retry; ftpClient.RetryAttempts = 3; try { return(ftpClient.UploadFile(source, target, existsMode, createDirectoryStructure, verifyMode) == true ? new DFtpResult(DFtpResultType.Ok) : // Return ok if upload okay. new DFtpResult(DFtpResultType.Error)); // Return error if upload fail. } catch (Exception ex) { return(new DFtpResult(DFtpResultType.Error, ex.Message)); // FluentFTP didn't like something. } }
/// <summary> /// Begins an asynchronous operation to move a directory on the remote file system, from one directory to another. /// Always checks if the source directory exists. Checks if the dest directory exists based on the `existsMode` parameter. /// Only throws exceptions for critical errors. /// </summary> /// <param name="path">The full or relative path to the object</param> /// <param name="dest">The new full or relative path including the new name of the object</param> /// <param name="existsMode">Should we check if the dest directory exists? And if it does should we overwrite/skip the operation?</param> /// <param name="callback">Async callback</param> /// <param name="state">State object</param> /// <returns>IAsyncResult</returns> public IAsyncResult BeginMoveDirectory(string path, string dest, FtpExists existsMode, AsyncCallback callback, object state) { AsyncMoveDirectory func; IAsyncResult ar; lock (m_asyncmethods) { ar = (func = MoveDirectory).BeginInvoke(path, dest, existsMode, callback, state); m_asyncmethods.Add(ar, func); } return(ar); }
public bool AddFile(IO.Stream stream, string name, Directory directory, bool overwrite = false) { FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip; try { string remoteUri = IO.Path.Combine(directory.GetUri().AbsolutePath, name); return(client.Upload(stream, remoteUri, exists, createRemoteDir: true)); } catch (Exception e) { ExceptionHandler.LogException(e); } return(false); }
/// <summary> /// Moves a directory asynchronously on the remote file system from one directory to another. /// Always checks if the source directory exists. Checks if the dest directory exists based on the `existsMode` parameter. /// Only throws exceptions for critical errors. /// </summary> /// <param name="path">The full or relative path to the object</param> /// <param name="dest">The new full or relative path including the new name of the object</param> /// <param name="existsMode">Should we check if the dest directory exists? And if it does should we overwrite/skip the operation?</param> /// <param name="token">Cancellation Token</param> /// <returns>Whether the directory was moved</returns> public async Task <bool> MoveDirectoryAsync(string path, string dest, FtpExists existsMode = FtpExists.Overwrite, CancellationToken token = default(CancellationToken)) { // verify args if (path.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "path"); } if (dest.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "dest"); } LogFunc(nameof(MoveDirectoryAsync), new object[] { path, dest, existsMode }); if (await DirectoryExistsAsync(path, token)) { // check if dest directory exists and act accordingly if (existsMode != FtpExists.NoCheck) { bool destExists = await DirectoryExistsAsync(dest, token); if (destExists) { switch (existsMode) { case FtpExists.Overwrite: await DeleteDirectoryAsync(dest, token); break; case FtpExists.Skip: return(false); } } } // move the directory await RenameAsync(path, dest, token); return(true); } return(false); }
public override bool Write(string fileName, byte[] data) { try { FtpExists overwriteMode = FtpExists.Skip; if (Overwrite) { overwriteMode = FtpExists.Overwrite; } EstablishFTPConnection(); FTPControl.Upload(data, fileName, overwriteMode); return(true); } catch { return(false); } }
/// <summary> /// Moves a directory on the remote file system from one directory to another. /// Always checks if the source directory exists. Checks if the dest directory exists based on the `existsMode` parameter. /// Only throws exceptions for critical errors. /// </summary> /// <param name="path">The full or relative path to the object</param> /// <param name="dest">The new full or relative path including the new name of the object</param> /// <param name="existsMode">Should we check if the dest directory exists? And if it does should we overwrite/skip the operation?</param> /// <returns>Whether the directory was moved</returns> public bool MoveDirectory(string path, string dest, FtpExists existsMode = FtpExists.Overwrite) { // verify args if (path.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "path"); } if (dest.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "dest"); } LogFunc("MoveDirectory", new object[] { path, dest, existsMode }); if (DirectoryExists(path)) { // check if dest directory exists and act accordingly if (existsMode != FtpExists.NoCheck) { var destExists = DirectoryExists(dest); if (destExists) { switch (existsMode) { case FtpExists.Overwrite: DeleteDirectory(dest); break; case FtpExists.Skip: return(false); } } } // move the directory Rename(path, dest); return(true); } return(false); }
public bool Copy(IFileSystemItem item, Directory directory, bool overwrite) { FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip; try { if (item.IsDirectory()) { client.CreateDirectory(IO.Path.Combine(directory.GetUri().AbsolutePath, item.Name)); } else { IO.MemoryStream stream = GetFileStream(item as File); return(client.Upload(stream, directory.GetUri().AbsolutePath, exists)); } } catch (Exception e) { ExceptionHandler.LogException(e); } return(false); }
public bool Move(IFileSystemItem item, Directory destDirectory, bool overwrite = false) { FtpExists exists = overwrite ? FtpExists.Overwrite : FtpExists.Skip; string destPath = destDirectory.GetUri().AbsolutePath; try { if (item.IsDirectory()) { return(client.MoveDirectory(item.GetUri().AbsolutePath, destPath, exists)); } else { return(client.MoveFile(item.GetUri().AbsoluteUri, destPath, exists)); } } catch (Exception e) { ExceptionHandler.LogException(e); } return(false); }
static void Main(string[] args) { try { if (args.Length <= 0) { Console.Write("Host: "); host = Console.ReadLine(); Console.Write("Port: "); port = Console.ReadLine(); Console.Write("User: "******"Pass: "******"Source Folder: "); sourcePath = Console.ReadLine(); Console.Write("Remote Folder: "); remotePath = Console.ReadLine(); Console.Write("Clean Remote Path (Y/n): "); cleanRemotePath = new List <string>() { "y", "yes" }.Any(key => Console.ReadLine().ToLower().Equals(key)); Console.Write("Exist File Option (append/overwirte/skip): "); ftpExists = (FtpExists)Enum.Parse(typeof(FtpExists), Console.ReadLine().FirstCharToUpper()); } else { for (int i = 0; i < args.Length; i++) { string param = args[i].Remove(args[i].IndexOf('=') + 1); string value = args[i].Substring(args[i].IndexOf('=') + 1); switch (param) { case "--host=": host = value; break; case "--port=": port = value; break; case "--user="******"--pass="******"--source=": sourcePath = Console.ReadLine(); break; case "--remote=": remotePath = Console.ReadLine(); break; case "--clean_remote=": cleanRemotePath = new List <string>() { "y", "yes" }.Any(key => value.ToLower().Equals(key)); i++; break; case "--exist_action=": ftpExists = (FtpExists)Enum.Parse(typeof(FtpExists), value.FirstCharToUpper()); i++; break; } } } } catch (Exception ex) { Log(contents: "Error input.", messageType: MessageType.ERROR); Log(contents: ex.Message, messageType: MessageType.ERROR); Console.WriteLine(); return; } Log(contents: "Start processing"); long beginTick = DateTime.Now.Ticks; if (!System.IO.Directory.Exists(sourcePath)) { Log(contents: $@"Can NOT match the source folder ""{ sourcePath }""", messageType: MessageType.ERROR); } else { sourcePath = System.IO.Path.GetFullPath(sourcePath).Replace('\\', '/'); remotePath = $"/{ remotePath.Replace('\\', '/').TrimStart('/') }"; try { var ftpClient = new FtpClient() { Host = host, Port = string.IsNullOrEmpty(port) ? 21 : int.Parse(port), RetryAttempts = 3 }; if (!string.IsNullOrEmpty(user)) { ftpClient.Credentials = new System.Net.NetworkCredential(user, pass); } Log(contents: $"Try to connect { host }:{ port }"); ftpClient.Connect(); Log(contents: "Connected successfully"); // Clean if (cleanRemotePath) { foreach (var item in ftpClient.GetListing(remotePath)) { for (int i = 1; i <= 3; i++) { try { if (item.Type == FtpFileSystemObjectType.Directory) { ftpClient.DeleteDirectory(item.FullName, FtpListOption.AllFiles); } if (item.Type == FtpFileSystemObjectType.File) { ftpClient.DeleteFile(item.FullName); } Log(contents: $"Deleted: ", writeMode: WriteMode.Append); Log(contents: $"{ item.Name }{ (item.Type == FtpFileSystemObjectType.Directory ? "/" : "") }", messageType: MessageType.PATH, withTitle: false, onlyTitleColor: false); break; } catch (Exception ex) { Log(contents: $"Deleted: ", messageType: MessageType.ERROR, writeMode: WriteMode.Append); Log(contents: $"{ item.Name }{ (item.Type == FtpFileSystemObjectType.Directory ? "/" : "") }", messageType: MessageType.PATH, withTitle: false, onlyTitleColor: false); Log(contents: ex.Message, messageType: MessageType.ERROR); System.Threading.Tasks.Task.Delay(1000).Wait(); } } } } // Upload int successCount = 0, failureCount = 0; foreach (var file in System.IO.Directory.GetFiles(sourcePath, "*", System.IO.SearchOption.AllDirectories)) { string remoteFile = file .Replace('\\', '/') .Replace(sourcePath, remotePath); try { if (ftpClient.UploadFile(localPath: file, remotePath: remoteFile, createRemoteDir: true, existsMode: ftpExists, verifyOptions: FtpVerify.Retry)) { successCount++; Log(contents: $"Uploaded: ", writeMode: WriteMode.Append); Log(contents: $"{ remoteFile }", messageType: MessageType.PATH, withTitle: false, onlyTitleColor: false); } else { failureCount++; Log(contents: $"Uploaded: ", messageType: MessageType.ERROR, writeMode: WriteMode.Append); Log(contents: $"{ remoteFile }", messageType: MessageType.PATH, withTitle: false, onlyTitleColor: false); } } catch (Exception ex) { failureCount++; Log(contents: $"Uploaded: ", messageType: MessageType.ERROR, writeMode: WriteMode.Append); Log(contents: $"{ remoteFile }", messageType: MessageType.PATH, withTitle: false, onlyTitleColor: false); Log(contents: ex.Message, messageType: MessageType.ERROR); } } ftpClient.Disconnect(); // Summary Log(contents: $"{ successCount + failureCount } files uploaded (", messageType: MessageType.INFO, withTitle: true, writeMode: WriteMode.Append); Log(contents: $"success: { successCount }", messageType: MessageType.INFO, withTitle: false, onlyTitleColor: false, writeMode: WriteMode.Append); Log(contents: $" / ", messageType: MessageType.NONE, withTitle: false, onlyTitleColor: false, writeMode: WriteMode.Append); Log(contents: $"faliure: { failureCount }", messageType: MessageType.ERROR, withTitle: false, onlyTitleColor: false, writeMode: WriteMode.Append); Log(contents: $") in", messageType: MessageType.NONE, withTitle: false, onlyTitleColor: false, writeMode: WriteMode.Append); Log(contents: $" { new TimeSpan(DateTime.Now.Ticks - beginTick).TotalSeconds.ToString("0.##") } s", messageType: MessageType.TIME, withTitle: false, onlyTitleColor: false, writeMode: WriteMode.Append); } catch (Exception ex) { Log(contents: ex.Message, messageType: MessageType.ERROR); } } Console.WriteLine(); }