List <ITransfer> IClientFtp.ListFileFolder(string unDossier) { List <FtpItem> lesFtpElements = new List <FtpItem>(); List <ITransfer> lesElements = new List <ITransfer>(); using (Ftp monFtp = new Ftp()) { monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(unDossier, _maConfig.GetUriChaine()); if (!string.IsNullOrEmpty(resteChemin)) { monFtp.ChangeFolder(resteChemin); } lesFtpElements = monFtp.GetList(); monFtp.Close(); } foreach (FtpItem unFtpItem in lesFtpElements) { if (unFtpItem.IsFile) { lesElements.Add(new ElementFile(unFtpItem, Path.Combine(unDossier, unFtpItem.Name))); } } return(lesElements); }
/// <summary> /// ftp transfer /// </summary> /// <param name="content">ftp content</param> /// <param name="sftpSetting">ftp setting</param> /// <returns></returns> bool FTPTransfer(string content, SFTPSetting sftpSetting) { try { _logger.LogInformation($"ftp begin"); using (var ftp = new Ftp()) { ftp.Connect(sftpSetting.Host); ftp.Login(sftpSetting.UserName, sftpSetting.Password); ftp.Mode = FtpMode.Active; ftp.ChangeFolder(sftpSetting.TransferDirectory); var encoding = Encoding.GetEncoding(sftpSetting.FileEncoding); var response = ftp.Upload($"{sftpSetting.TransferFilePrefix}{sftpSetting.FileName}", 0, encoding.GetBytes(content)); if (response.Code.HasValue && (response.Code.Value == 226 || response.Code.Value == 200)) { ftp.Close(); _logger.LogInformation($"ftp uplodad success"); return(true); } else { _logger.LogError($"ftp uplodad failure,because:{response.Message}"); ftp.Close(); return(false); } } } catch (Exception exc) { _logger.LogCritical(exc, $"ftp uplodad failure:{exc.Message}"); return(false); } }
public void Upload() { using (Ftp ftp = new Ftp()) { ftp.Connect("ftp.ciotems.com"); ftp.Login("collector", "Cete@712"); ftp.ChangeFolder("logs"); ftp.Upload("logs.txt", @"D:\桌面\新建文件夹\log.txt.2"); ftp.Close(); } }
public void CreerDossier(string leNmDossierACreer, ElementFolder leDossierDistant) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(leDossierDistant.GetPath(), _maConfig.GetUriChaine()); _monFtp.ChangeFolder(resteChemin); _monFtp.CreateFolder(leNmDossierACreer); _monFtp.Close(); } }
public bool Download(ElementFolder remoteFolder, ElementFile remoteFile, ElementFolder localFolder) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteCheminFolder = remoteFolder.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); string resteCheminFichier = remoteFile.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); _monFtp.ChangeFolder(resteCheminFolder); _monFtp.Download(remoteFile.GetName(), Path.Combine(localFolder.GetPath(), remoteFile.GetName())); _monFtp.Close(); } return(true); }
private static string _logFolder = "myLogs"; //Folder with logs on FTP server public static void Send(MemoryStream ms) { try// { Console.WriteLine("Start loading log on FTP."); byte[] bt = ms.GetBuffer(); FileStream fs = new FileStream("", FileMode.Create); fs.Write(bt, 0, bt.Length); Ftp ftp = new Ftp(); ftp.Connect(_ipAddress); ftp.Login(_login, _password); ftp.ChangeFolder(_logFolder); ftp.UploadUnique(ms); ftp.UploadUnique(bt); } catch { } }
public bool Upload(ElementFolder localFolder, ElementFile localFile, ElementFolder distantFolder) { FtpResponse maReponseFtp; using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = distantFolder.GetPath().Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); if (!string.IsNullOrEmpty(resteChemin)) { _monFtp.ChangeFolder(resteChemin); } maReponseFtp = _monFtp.Upload(localFile.GetName(), localFile.GetPath()); _monFtp.Close(); } return(true); }
private void FTPConnect(Ftp ftp) { //Limilabs.FTP.Log.Enabled = true; ftp.Connect(this.HostIP); log.Info(string.Format("Connected to FTP [{0}]", this.HostIP)); try { ftp.Login(this.UserName, this.Pass); log.Info(string.Format("Loggedin using [{0}] [{1}]", this.UserName, this.Pass)); } catch { ftp.LoginAnonymous(); log.Info("Login Anonymous"); } if (!string.IsNullOrEmpty(this.FolderPath)) { ftp.ChangeFolder(this.FolderPath); } }
public bool Process( string uploadPath, ConnectionSettings connection) { var processLog = new StringBuilder(); var uploadGroupPath = Path.Combine(uploadPath, _webLocationFolderName); if (!Directory.Exists(uploadGroupPath)) { Directory.CreateDirectory(uploadGroupPath); } var uploadSitePath = Path.Combine(uploadGroupPath, Path.GetFileName(_sourcePath)); var currentFolder = _sourcePath; bool completedSuccessFully; try { processLog.AppendLine(String.Format("iSpring tune process started at folder {0}", _sourcePath)); var webContentPath = Path.Combine(_sourcePath, WebContentFolderName); var convertedFolderName = (WebContentFolderName.Replace(" ", " ") .Replace(" ", " ") .Replace(" ", "_") .Replace("(", "") .Replace(")", "") + _id) .ToLower(); var destinationFolderPath = Path.Combine(_sourcePath, convertedFolderName); if (!String.Equals(webContentPath, destinationFolderPath, StringComparison.OrdinalIgnoreCase)) { try { Directory.Move(webContentPath, destinationFolderPath); } catch (Exception ex) { throw new UnauthorizedAccessException(String.Format("Error while change folder name with {0}{1}{2}", convertedFolderName, ex.Message, Environment.NewLine)); } } processLog.AppendLine(String.Format("Folder name changed with {0}", convertedFolderName)); var dataFolderPath = Path.Combine(destinationFolderPath, DataFolderName); if (!Directory.Exists(dataFolderPath)) { throw new FileNotFoundException(String.Format("Site Data folder {0} not found", dataFolderPath)); } File.WriteAllText(Path.Combine(dataFolderPath, JqueryFileName), Properties.Resources.JQueryFileContent); processLog.AppendLine(String.Format("File added {0}", JqueryFileName)); File.WriteAllText(Path.Combine(dataFolderPath, JsonFileName), Properties.Resources.JSonFileContent); processLog.AppendLine(String.Format("File added {0}", JsonFileName)); File.WriteAllText(Path.Combine(dataFolderPath, MetroNotificationScriptFileName), Properties.Resources.MetroNotificationScriptFileContent); processLog.AppendLine(String.Format("File added {0}", MetroNotificationScriptFileName)); File.WriteAllText(Path.Combine(dataFolderPath, MetroNotificationStyleFileName), Properties.Resources.MetroNotificationStyleFileContent); processLog.AppendLine(String.Format("File added {0}", MetroNotificationStyleFileName)); File.WriteAllText(Path.Combine(dataFolderPath, FontAwesomeStyleFileName), Properties.Resources.FontAwesomeStyleContent); processLog.AppendLine(String.Format("File added {0}", FontAwesomeStyleFileName)); var activityRegularFileContent = Properties.Resources.ActivityRegularFileContent; activityRegularFileContent = activityRegularFileContent.Replace(SitePathPlaceHolder, connection.Url); activityRegularFileContent = activityRegularFileContent.Replace(EmailPlaceHolder, String.Join(";", _emails)); activityRegularFileContent = activityRegularFileContent.Replace(AdvertiserPlaceHolder, _advertiserName.Replace("'", @"\'")); File.WriteAllText(Path.Combine(dataFolderPath, ActivityRegularFileName), activityRegularFileContent); processLog.AppendLine(String.Format("File added {0}", ActivityRegularFileName)); var activityLoginFileContent = Properties.Resources.ActivityLoginFileContent; activityLoginFileContent = activityLoginFileContent.Replace(AdvertiserPlaceHolder, _advertiserName.Replace("'", @"\'")); activityLoginFileContent = activityLoginFileContent.Replace(FileNamePlaceHolder, String.Format("{0}.pptx", Name)); File.WriteAllText(Path.Combine(dataFolderPath, ActivityLoginFileName), activityLoginFileContent); processLog.AppendLine(String.Format("File added {0}", ActivityLoginFileName)); File.WriteAllText(Path.Combine(destinationFolderPath, LoginIndexFileName), Properties.Resources.LoginIndexFileContent); processLog.AppendLine(String.Format("File added {0}", LoginIndexFileName)); var originalIndexFilePath = Path.Combine(destinationFolderPath, OriginalIndexFileName); var publicIndexFilePath = Path.Combine(destinationFolderPath, PublicIndexFileName); if (!File.Exists(originalIndexFilePath)) { throw new FileNotFoundException(String.Format("Site Index file not found")); } var indexFileContent = File.ReadAllText(originalIndexFilePath); File.Delete(originalIndexFilePath); var originalHeadContent = String.Empty; var matches = Regex.Matches(indexFileContent, @"<head>([.\S+\n\r\s]*?)<\/head>"); if (matches.Count > 0 && matches[0].Groups.Count > 1) { originalHeadContent = matches[0].Groups[1].Value; } if (!String.IsNullOrEmpty(originalHeadContent)) { if (!originalHeadContent.Contains(Properties.Resources.PublicIndexScriptIncludePart)) { var modifiedHeadContent = String.Format("{0}{2}{1}", originalHeadContent, Properties.Resources.PublicIndexScriptIncludePart, Environment.NewLine); File.WriteAllText(publicIndexFilePath, indexFileContent.Replace(originalHeadContent, modifiedHeadContent)); } } processLog.AppendLine("Web Folder html file new code added"); Directory.Move(_sourcePath, uploadSitePath); currentFolder = uploadSitePath; processLog.AppendLine(String.Format("CWL PACK Moved to Upload folder ({0})", uploadSitePath)); using (var ftp = new Ftp()) { ftp.Connect(connection.FtpUrl); ftp.Login(connection.Login, connection.Password); ftp.ChangeFolder(FtpRootFolder); ftp.CreateFolder(_webLocationFolderName); ftp.ChangeFolder(_webLocationFolderName); ftp.CreateFolder(convertedFolderName); ftp.UploadFiles(convertedFolderName, Path.Combine(uploadSitePath, convertedFolderName)); ftp.Close(); } processLog.AppendLine("Web Folder uploaded with web services to clientweblink.com"); OutlookHelper.Instance.SendMessage( String.Format("HTML5 presentation ready for {0}", _advertiserName), String.Format("Your HTML5 Web Link is ready for: {0}{3}{3}" + "Public URL{3}{1}{3}{3}" + "Client Login URL{3}{2}{3}{3}" + "*Please Note:{3}You will receive a confirmation email each time someone views this presentation.{3}{3}{3}" + "If you have any technical issues with your HTML5 web link, then email:{3}[email protected]", _advertiserName, String.Format("{0}/{1}/{2}/{3}/{4}", connection.Url, SiteRootFolder, _webLocationFolderName, convertedFolderName, PublicIndexFileName), String.Format("{0}/{1}/{2}/{3}/{4}", connection.Url, SiteRootFolder, _webLocationFolderName, convertedFolderName, LoginIndexFileName), Environment.NewLine), _emails); processLog.AppendLine(String.Format("Confirmation email with URL sent to {0}", String.Join(";", _emails))); processLog.AppendLine("iSpring tune process completed successfully"); completedSuccessFully = true; } catch (Exception ex) { processLog.AppendLine("iSpring tune process completed unsuccessfully"); processLog.AppendLine(ex.Message); processLog.AppendLine(ex.StackTrace); completedSuccessFully = false; } finally { var logFilePath = Path.Combine(currentFolder, LogFileName); File.WriteAllText(logFilePath, processLog.ToString()); } return(completedSuccessFully); }
public List <ITransfer> ListFolder(string cheminFTPDossier) { List <FtpItem> lesFtpElements = new List <FtpItem>(); List <ITransfer> lesElements = new List <ITransfer>(); //StatusCommand lesStatuts = new StatusCommand(EStatusCommand); using (_monFtp = new Ftp()) { VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeConnexion)); try { _monFtp.Connect(_maConfig.Host, _maConfig.Port); // or ConnectSSL for SSL VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AReussieAjoindreHote)); } catch (Exception) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ImpossibleDAtteindreServeurFtp)); } VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeAuthentification)); try { _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AuthentificationReussie)); } catch (FtpResponseException e) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.AuthentificationReussie)); } string resteChemin = cheminFTPDossier.Replace(_maConfig.GetUriChaine(), "").Replace(@"\", "/"); if (resteChemin.Equals("")) { VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.RepertoireInexistant)); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.RepertoireParDefautDefini)); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeListDossier)); VariablesGlobales._leLog.LogCustom(string.Format("Demande de la liste des dossiers de : {0}", _maConfig.GetUriChaine()), true); lesFtpElements = _monFtp.GetList(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ListeTrouvee)); } else { List <string> larbo = resteChemin.Split(new char[] { '/' }).ToList(); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeChangementRepertoire)); if (larbo.Count > 0) { _monFtp.ChangeFolder(resteChemin); } else { _monFtp.ChangeFolder(resteChemin); } VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ChangementRepertoireEffectue)); VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeListDossier)); VariablesGlobales._leLog.LogCustom(string.Format("Demande de la liste des dossiers de : {0}", resteChemin), true); lesFtpElements = _monFtp.GetList(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.ListeTrouvee)); } VariablesGlobales._leLog.Log(new StatusCommand(EStatusCommand.DemandeFermetureFluxEchange)); _monFtp.Close(); VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.FermetureDuFluxReussie)); } VariablesGlobales._leLog.Log(new StatusResponse(EStatusResponse.GenerationElementTransferables)); foreach (FtpItem unFtpItem in lesFtpElements) { if (unFtpItem.IsFolder) { lesElements.Add(new ElementFolder(unFtpItem, Path.Combine(cheminFTPDossier, unFtpItem.Name))); } } return(lesElements); }
public List<string> GetFilesNamesFromFTP(string host, int port, string remoteFolderPath, string localFolderPath, string username, string password, List<string> userCodesList) { //host="83.12.64.6"; //port = 12024; //username = "******"; //password="******"; //remoteFolderPath = "Test2"; //localFolderPath = @"C:\"; //remoteFolderPath = ""; //userCodesList = new List<string>(); //userCodesList.Add("PL0091"); List<string> filesList = new List<string>(); try { using (Ftp client = new Ftp()) { client.Connect(host, port); // or ConnectSSL for SSL client.Login(username, password); //client.Download(@"reports\report.txt", @"c:\report.txt"); //client.DownloadFiles(remoteFolderPath, localFolderPath); //RemoteSearchOptions option = new RemoteSearchOptions("*.xml", true); //client.DeleteFiles(remoteFolderPath, option); //client.DeleteFolder(remoteFolderPath); //client.CreateFolder(remoteFolderPath); //byte[] bytes = client.Download(@"reports/report.txt"); //string report = Encoding.UTF8.GetString(bytes,0,bytes.Length); client.ChangeFolder(remoteFolderPath); List<FtpItem> items = client.GetList(); foreach (FtpItem item in items) { if (item.IsFile) { filesList.Add(item.Name); /* string filePath = localFolderPath + "\\" + item.Name; currentFileName = item.Name; if (!File.Exists(filePath)) { byte[] bytes = client.Download(item.Name); //string xelementString = Encoding.UTF8.GetString(bytes,0,bytes.Length); //xelementString = getRidOfUnprintablesAndUnicode(xelementString); MemoryStream stream = new MemoryStream(bytes); XElement xelement = XElement.Load(stream);//XElement.Parse(xelementString); xelement.Save(filePath); downloadedFilesCount++; } var sender = (from nm in xelement.Elements("Sender") select nm).FirstOrDefault(); string code = sender.Element("Code").Value; code = userCodesList.Where(c=>c==code).FirstOrDefault(); if (code != null) { xelement.Save(localFolderPath + "\\" + item.Name,); client.DeleteFile(item.Name); downloadedFilesCount++; } */ } } client.Close(); } } catch (Exception ex) { return new List<string> { "error-"+ex.Message}; } return filesList; }
public string GetFileFromFTP(string host, int port, string remoteFolderPath, string localFolderPath, string username, string password, List<string> userCodesList, string fileName) { //host="83.12.64.6"; //port = 12024; //username = "******"; //password="******"; //remoteFolderPath = "Test2"; //localFolderPath = @"C:\"; //remoteFolderPath = ""; //userCodesList = new List<string>(); //userCodesList.Add("PL0091"); try { using (Ftp client = new Ftp()) { client.Connect(host, port); // or ConnectSSL for SSL client.Login(username, password); client.ChangeFolder(remoteFolderPath); string filePath = localFolderPath + "\\" + fileName; if (!File.Exists(filePath)) { byte[] bytes = client.Download(fileName); MemoryStream stream = new MemoryStream(bytes); XElement xelement = XElement.Load(stream);//XElement.Parse(xelementString); xelement.Save(filePath); } client.Close(); } } catch(Exception ex) { return "error-"+ex.Message; } return "ok";//+ " plików dla kodów "+codesString; }