public void DeleteDirectory(string remotePath) { Connect(); string filename = FTPHelpers.GetFileName(remotePath); if (filename == "." || filename == "..") { return; } FtpItemCollection files = GetDirList(remotePath); foreach (FtpItem file in files) { if (file.ItemType == FtpItemType.Directory) { DeleteDirectory(file.FullPath); } else { DeleteFile(file.FullPath); } } Client.DeleteDirectory(remotePath); }
public static List <FileSystemFTPInfo> ConvertFrom(FtpItemCollection results, FtpClientExt ftpCmdInstance) { List <FileSystemFTPInfo> _list = new List <FileSystemFTPInfo>(results.Count); foreach (FtpItem item in results) { FileSystemFTPInfo info = (item.ItemType == FtpItemType.Directory) ? (FileSystemFTPInfo) new DirectoryFTPInfo(ftpCmdInstance, item.FullPath) : new FileFTPInfo(ftpCmdInstance, item.FullPath); // Set it to be offline to allow explorer some extra time to find details before timg out. info.attributes = (item.ItemType == FtpItemType.Directory) ? FileAttributes.Directory : FileAttributes.Offline; if (item.Attributes[0] == 'l') { info.attributes |= FileAttributes.ReparsePoint; } // drwx- if ((item.Attributes[1] == 'r') && (item.Attributes[2] != 'w') ) { info.attributes |= FileAttributes.ReadOnly; } info.length = item.Size; info.creationTimeUtc = item.Modified; info.lastWriteTimeUtc = item.Modified; _list.Add(info); } return(_list); }
public List <File_info> GetFilesList(string dir) { List <File_info> res = new List <File_info>(); if (!this.ftp.IsConnected) { return(res); } if (!string.IsNullOrEmpty(dir)) { try { this.ftp.ChangeDirectory(dir); } catch (Exception ex) { if (this.errorLog != null) { this.errorLog.Add("RebexFTPsource error 2", "Directory error:\n" + ex.ToString()); } return(res); } } FtpItemCollection fi_coll = null; try { fi_coll = this.ftp.GetList(); } catch (Exception ex) { if (this.errorLog != null) { this.errorLog.Add("RebexFTPsource error 1", "GetList failed:\n" + ex.ToString()); } return(res); } foreach (FtpItem item in fi_coll) { File_info fi = new File_info(item.Name); res.Add(fi); fi.mod_time = item.Modified; fi.size = item.Length; } return(res); }
public bool IsValidLicense() { if (!lastLicenseCheck.HasValue || lastLicenseCheck.Value.AddMonths(1) < DateTime.Today) { EmpresasBL empBL = new EmpresasBL(); empBL.SetParameters(db); ComprobantesBL compBL = new ComprobantesBL(); compBL.SetParameters(db); Empresas empresa = empBL.GetObject(GeneralSettings.Instance.IdEmpresaDefault) as Empresas; if (empresa != null) { Ftp FtpClient = new Ftp(); FtpClient.HostAddress = FTPHost; FtpClient.Port = FTPPort; FtpClient.Username = FTPName; FtpClient.Password = FTPPass; FtpClient.Timeout = FTPTimeOut; FtpClient.Connect(); string fileName = empresa.Cuit; FtpClient.MoveDirectory("Licencias"); FtpItemCollection fic = new FtpItemCollection(); FtpClient.FileList(ref fic); foreach (FtpItem item in fic) { if (item.Name.ToLower() == fileName.ToLower()) { lastLicenseCheck = DateTime.Today; return(true); } } FtpClient.Quit(); } return(false); } else { return(true); } }
private void ShowFiles() { DataTable dt = new DataTable(); dt.Columns.Add("Type"); dt.Columns.Add("Name"); dt.Columns.Add("Mod Date"); dt.Columns.Add("Size", typeof(int)); FtpItemCollection list = null; try { list = this.ftp.GetList(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } foreach (FtpItem item in list) { DataRow row = dt.Rows.Add(); if (item.IsSymlink) { row["Type"] = "SysLink"; } else if (item.IsDirectory) { row["Type"] = "Dir"; } else { row["Type"] = "File"; } row["Name"] = item.Name; row["Mod Date"] = item.Modified; row["Size"] = item.Length; } this.main_ultraGrid.DataSource = dt; }
public IEnumerable <FtpItem> ListDirectoriesAndFiles(string path, bool recursive) { var ftp = new FtpClient(Host, Port, Protocol) { DataTransferMode = UsePassiveMode ? TransferMode.Passive : TransferMode.Active, FileTransferType = TransferType.Binary, Proxy = Proxy != null ? new HttpProxyClient(Proxy.Address.ToString()) : null }; try { ftp.Open(Username, Password.ConvertToUnsecureString()); FtpItemCollection items = recursive ? ftp.GetDirListDeep(path) : ftp.GetDirList(path); return(items); } finally { ftp.Close(); } }
/// <summary> /// Get as many details as it can about the target. /// </summary> /// <param name="target">If empty then will assume CWD has been used</param> /// <returns>May return null if nothing found</returns> public FileSystemFTPInfo GetFileDetails(string target) { List <FileSystemFTPInfo> foundValues; lock (commandLock) { // replace the windows style directory delimiter with a unix style delimiter target = NormaliseForFTP(target); Features featureToUse = ((SupportedFeatures & Features.MLST) == Features.MLST) ? Features.MLST : Features.LIST; if (featureToUse == Features.MLST) { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.RequestedFileActionOkayAndCompleted, FtpResponseCode.SyntaxErrorInParametersOrArguments // Stop using exceptions to detect missing ); } else { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.DataConnectionAlreadyOpenSoTransferStarting, FtpResponseCode.FileStatusOkaySoAboutToOpenDataConnection, FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted ); } FtpResponseCollection dirResults = (string.IsNullOrEmpty(target)) ? Feature((featureToUse != Features.MLST), featureToUse) : Feature((featureToUse != Features.MLST), featureToUse, true, target); if (featureToUse == Features.MLST) { foundValues = new MlstCollection(this, target, dirResults); } else { // Do it the harder way ?? FtpItemCollection results = new FtpItemCollection(target, dirResults.GetRawText(), ftpInstance.ItemParser); foundValues = FileSystemFTPInfo.ConvertFrom(results, this); } } return(foundValues.Count > 0 ? foundValues[0] : null); }
public override int Run(string[] paths) { //this.path = paths[0]; this.path = paths[0].Replace(@"\", "/"); Console.WriteLine(path); // create a new FtpClient object with the host and port number to use // (optionally create a secure SSL connection) ftp = new Starksoft.Net.Ftp.FtpClient(host, 21); // specify a binary, passive connection with no zlib file compression ftp.FileTransferType = TransferType.Binary; ftp.DataTransferMode = TransferMode.Passive; // open a connection to the ftp server ftp.Open(username, password); // change to the directory on the ftp server specified in cmd line option //ftp.ChangeDirectory(path); // retrieve a listing of the files in the directory as a collection of FtpItem objects FtpItemCollection col = new FtpItemCollection(); if (string.IsNullOrEmpty(recurse)) { col = ftp.GetDirList(path); } else { col = ftp.GetDirListDeep(path); } foreach (FtpItem item in col) { Console.WriteLine("{0}\t{1}\t{2}", item.Modified.ToString(), item.ItemType.ToString(), item.FullPath); } // close connection to the ftp server ftp.Close(); return 0; }
public void TestGetDirList(string host, int port, FtpSecurityProtocol protocol, string user, string pwd, string server) { using (FtpClient c = new FtpClient(host, port, protocol)) { c.AlwaysAcceptServerCertificate = true; c.Open(user, pwd); Assert.IsTrue(c.IsConnected); FtpItemCollection lst = c.GetDirList(); Debug.WriteLine("==================================================="); Debug.WriteLine("DIRECTORY DUMP"); Debug.WriteLine("==================================================="); foreach (FtpItem item in lst) { Debug.WriteLine(item.RawText); Debug.WriteLine(item.ToString()); } Debug.WriteLine("==================================================="); } }
private void FTPDownload(bool openDirectory) { if (lvFTPList.SelectedItems.Count > 0) { FtpItem checkDirectory = lvFTPList.SelectedItems[0].Tag as FtpItem; if (openDirectory && checkDirectory != null) { if (checkDirectory.ItemType == FtpItemType.Unknown && checkDirectory.Name == "..") { FTPNavigateBack(); return; } if (checkDirectory.ItemType == FtpItemType.Directory) { LoadDirectory(checkDirectory.FullPath); return; } } FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.RootFolder = Environment.SpecialFolder.Desktop; if (fbd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(fbd.SelectedPath)) { FtpItemCollection list = new FtpItemCollection(); foreach (ListViewItem lvi in lvFTPList.SelectedItems) { FtpItem file = lvi.Tag as FtpItem; if (file != null) { list.Add(file); } } FTPAdapter.DownloadFiles(list, fbd.SelectedPath); } } }
//public bool ChangeDirectory(string path) //{ // if (path == null) // throw new ArgumentNullException("path"); // if (path.Length == 0) // throw new ArgumentException("must have a value", "path"); // // replace the windows style directory delimiter with a unix style delimiter // path = NormaliseForFTP( path ); // lock (commandLock) // { // FtpRequest request = new FtpRequest(FtpCmd.Cwd, ftpInstance.CharacterEncoding, path) // { // HappyCodes = // FtpRequest.BuildResponseArray( // FtpResponseCode.RequestedFileActionOkayAndCompleted, // FtpResponseCode.RequestedActionNotTakenFileUnavailable // ) // }; // CheckConnected(); // ftpInstance.SendRequest(request); // return ftpInstance.LastResponse.Code == FtpResponseCode.RequestedFileActionOkayAndCompleted; // } //} public List <FileSystemFTPInfo> GetDirList(string path) { List <FileSystemFTPInfo> foundValues; lock (commandLock) { // replace the windows style directory delimiter with a unix style delimiter path = NormaliseForFTP(path); Features featureToUse = ((SupportedFeatures & Features.MLSD) == Features.MLSD) ? Features.MLSD : Features.LIST; if (featureToUse == Features.MLSD) { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted); } else { happyCodes = FtpRequest.BuildResponseArray(FtpResponseCode.DataConnectionAlreadyOpenSoTransferStarting, FtpResponseCode.FileStatusOkaySoAboutToOpenDataConnection, FtpResponseCode.ClosingDataConnection, FtpResponseCode.RequestedFileActionOkayAndCompleted); } FtpResponseCollection dirResults = (string.IsNullOrEmpty(path)) ? Feature((featureToUse != Features.MLSD), featureToUse) : Feature((featureToUse != Features.MLSD), featureToUse, true, path); if (featureToUse == Features.MLSD) { foundValues = new MlstCollection(this, path, dirResults); } else { // Do it the harder way ?? FtpItemCollection results = new FtpItemCollection(path, dirResults.GetRawText(), ftpInstance.ItemParser); foundValues = FileSystemFTPInfo.ConvertFrom(results, this); } } return(foundValues); }
public void DownloadFiles(IEnumerable <FtpItem> files, string localPath) { foreach (FtpItem file in files) { if (file != null && !string.IsNullOrEmpty(file.Name)) { if (file.ItemType == FtpItemType.Directory) { FtpItemCollection newFiles = GetDirList(file.FullPath); string directoryPath = Path.Combine(localPath, file.Name); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } DownloadFiles(newFiles, directoryPath); } else if (file.ItemType == FtpItemType.File) { DownloadFile(file.FullPath, Path.Combine(localPath, file.Name)); } } } }
/// <summary> /// Initializes a new instance of the GetDirAsyncCompletedEventArgs class. /// </summary> /// <param name="error">Any error that occurred during the asynchronous operation.</param> /// <param name="canceled">A value indicating whether the asynchronous operation was canceled.</param> /// <param name="directoryListing">A FtpItemCollection containing the directory listing.</param> public GetDirListDeepAsyncCompletedEventArgs(Exception error, bool canceled, FtpItemCollection directoryListing) : base(error, canceled, null) { _directoryListing = directoryListing; }
/// <summary> /// Retrieves a list of the files from current working directory on the remote FTP /// server using the LIST command. /// </summary> /// <returns>FtpItemList collection object.</returns> /// <remarks> /// This method returns a FtpItemList collection of FtpItem objects. /// </remarks> /// <seealso cref="GetDirListAsync(string)"/> /// <seealso cref="GetDirListAsText(string)"/> /// <seealso cref="GetDirListDeep"/> /// <seealso cref="GetDirListDeepAsync(string)"/> /// <seealso cref="GetNameList(string)"/> public virtual FtpItemCollection GetDirList() { var items = new FtpItemCollection(_currentDirectory, base.TransferText(new FtpRequest(base.CharacterEncoding, FtpCmd.List, "-al")), _itemParser); items.SetTimeOffset(ServerTimeOffset); return items; }
private void ParseDirListDeep(string path, FtpItemCollection deepCol) { FtpItemCollection itemCol = GetDirList(path); deepCol.Merge(itemCol); foreach (FtpItem item in itemCol) { // if the this call is being completed asynchronously and the user requests a cancellation // then stop processing the items and return if (base.AsyncWorker != null && base.AsyncWorker.CancellationPending) return; // if the item is of type Directory then parse the directory list recursively if (item.ItemType == FtpItemType.Directory) ParseDirListDeep(item.FullPath, deepCol); } }
/// <summary> /// Deeply retrieves a list of all files and all sub directories from a specified path on the remote FTP /// server using the LIST command. /// </summary> /// <param name="path">The path to a directory on the remote FTP server.</param> /// <returns>FtpFileCollection collection object.</returns> /// <remarks> /// This method returns a FtpFileCollection object containing a collection of /// FtpItem objects. /// Note that some FTP servers will not accept a full path. On those systems you must navigate to /// the parent directory you wish to get the directory list using with the ChangeDirectory() or ChangeDirectoryMultiPath() /// method. /// </remarks> /// <seealso cref="GetDirListDeepAsync(string)"/> /// <seealso cref="GetDirList(string)"/> /// <seealso cref="GetDirListAsync(string)"/> /// <seealso cref="GetDirListAsText(string)"/> /// <seealso cref="GetNameList(string)"/> public FtpItemCollection GetDirListDeep(string path) { if (path == null) throw new ArgumentNullException("path"); FtpItemCollection deepCol = new FtpItemCollection(); ParseDirListDeep(path, deepCol); return deepCol; }
/// <summary> /// Retrieves a list of the files from a specified path on the remote FTP /// server using the LIST command. /// </summary> /// <param name="path">The path to a directory on the remote FTP server.</param> /// <returns>FtpFileCollection collection object.</returns> /// <remarks> /// This method returns a FtpFileCollection object containing a collection of /// FtpItem objects. Some FTP server implementations will not accept a full path to a resource. On those /// systems it is best to change the working directory using the ChangeDirectoryMultiPath(string) method and then call /// the method GetDirList(). /// </remarks> /// <seealso cref="GetDirListAsync(string)"/> /// <seealso cref="GetDirListAsText(string)"/> /// <seealso cref="GetDirListDeep"/> /// <seealso cref="GetDirListDeepAsync(string)"/> /// <seealso cref="GetNameList(string)"/> public virtual FtpItemCollection GetDirList(string path) { if (path == null) throw new ArgumentNullException("path"); var items = new FtpItemCollection(path, base.TransferText(new FtpRequest(base.CharacterEncoding, FtpCmd.List, "-al", path)), _itemParser); items.SetTimeOffset(ServerTimeOffset); return items; }
private void ParseDirListDeep(string path, FtpItemCollection deepCol) { FtpItemCollection itemCol = GetDirList(path); deepCol.Merge(itemCol); foreach (FtpItem item in itemCol) { if (base.AsyncWorker != null && base.AsyncWorker.CancellationPending) { return; } if (item.ItemType == FtpItemType.Directory) { ParseDirListDeep(item.FullPath, deepCol); } } }
/// <summary> /// Deeply retrieves a list of all files and all sub directories from a specified path on the remote FTP /// server using the LIST command. /// </summary> /// <param name="path">The path to a directory on the remote FTP server.</param> /// <returns>FtpFileCollection collection object.</returns> /// <remarks> /// This method returns a FtpFileCollection object containing a collection of /// FtpItem objects. /// Note that some FTP servers will not accept a full path. On those systems you must navigate to /// the parent directory you wish to get the directory list using with the ChangeDirectory() or ChangeDirectoryMultiPath() /// method. /// </remarks> /// <seealso cref="GetDirListDeepAsync(string)"/> /// <seealso cref="GetDirList(string)"/> /// <seealso cref="GetDirListAsync(string)"/> /// <seealso cref="GetDirListAsText(string)"/> /// <seealso cref="GetNameList(string)"/> public virtual FtpItemCollection GetDirListDeep(string path) { if (path == null) throw new ArgumentNullException("path"); FtpItemCollection deepCol = new FtpItemCollection(); ParseDirListDeep(path, deepCol); deepCol.SetTimeOffset(ServerTimeOffset); return deepCol; }
void PopulateServerList(string path) { FtpItemCollection items = _ftp.GetList(); int dirs = 0; int files = 0; long size = 0; // Clear the local list lvServer.Items.Clear(); // directory up if (path.Length > _rootServerDir.Length) { ListViewItem item = new ListViewItem("..", 1); int n = path.LastIndexOf('/'); item.Tag = new ListItemInfo(n > 0 ? path.Substring(0, n) : "/", true, true, false, false); lvServer.Items.Add(item); dirs++; } // Populate files and directories for (int c = 0; c < items.Count; c++) { string[] row = new string[5]; FtpItem dirInfo = items[c]; if (dirInfo.Name == "." || dirInfo.Name == "..") { continue; } row[0] = Path.GetFileNameWithoutExtension(dirInfo.Name); // Name row[1] = Path.GetExtension(dirInfo.Name); // Ext row[2] = Common.BytesToString(dirInfo.Length); // Size row[3] = Common.FormatTime(dirInfo.LastWriteTime); // Last Write Time if (dirInfo.Permissions != null) { row[4] = dirInfo.Permissions.ToString(); } ListViewItem item = new ListViewItem(row, 1 + c); item.Tag = new ListItemInfo(path.TrimEnd('/', '\\') + "/" + dirInfo.Name, false, dirInfo.IsDirectory, dirInfo.IsFile, dirInfo.IsLink); if (dirInfo.IsDirectory) { item.ImageIndex = 1; dirs++; } else if (dirInfo.IsFile) { item.ImageIndex = 0; files++; size += dirInfo.Length; } //else if (dirInfo.IsLink) //{ // item.ImageIndex = 2; //} lvServer.Items.Add(item); } // Update stats UpdateListStats(lbServerStats, dirs, files, size); }