/// <summary> /// Download Files /// </summary> private void DownloadFiles() { using (FtpConnection ftpConnection = this.CreateFtpConnection()) { if (!string.IsNullOrEmpty(this.WorkingDirectory)) { if (!Directory.Exists(this.WorkingDirectory)) { Directory.CreateDirectory(this.WorkingDirectory); } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory)); FtpConnection.SetLocalDirectory(this.WorkingDirectory); } ftpConnection.LogOn(); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } this.LogTaskMessage("Downloading Files"); if (this.FileNames == null) { FtpFileInfo[] filesToDownload = ftpConnection.GetFiles(); foreach (FtpFileInfo fileToDownload in filesToDownload) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileToDownload)); ftpConnection.GetFile(fileToDownload.Name, false); } } else { foreach (string fileName in this.FileNames.Select(item => item.ItemSpec.Trim())) { try { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Downloading: {0}", fileName)); ftpConnection.GetFile(fileName, false); } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error downloading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } } }
private static void DownloadDirectory(FtpConnection ftp, string p, string p_2) { string targetFolder = Path.GetFullPath(p_2); //string sourceFolder = ftp.GetCurrentDirectory() + '/' + p; DirectoryInfo localDir = new DirectoryInfo(targetFolder); if (localDir.Exists) { localDir.Delete(true); } localDir.Create(); ftp.SetCurrentDirectory(p); ftp.SetLocalDirectory(localDir.FullName); foreach (var file in ftp.GetFiles()) { string localFilename = localDir.FullName + Path.DirectorySeparatorChar + file.Name; if (File.Exists(localFilename)) { File.Delete(localFilename); } ftp.GetFile(file.Name, false); } foreach (var directory in ftp.GetDirectories()) { Directory.CreateDirectory(directory.Name); DownloadDirectory(ftp, directory.Name, targetFolder + Path.DirectorySeparatorChar + directory.Name); } ftp.SetCurrentDirectory(".."); }
/// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="remoteFile"></param> /// <returns></returns> public string download(string fileName, string remoteFile) { logger.pushOperation("FTP.download"); string ret = ""; try { //caso o arquivo exista, remove o arquivo existente antes de baixar o arquivo if (File.Exists(fileName)) { File.Delete(fileName); } sFTP.GetFile(remoteFile, fileName, true); if (File.Exists(fileName)) { ret = fileName; } } catch (Exception e) { ret = ""; logger.log("Erro ao conectar FTP: " + e.Message, Logger.LogType.ERROR, e, false); } finally { logger.releaseOperation(); } return(ret); }
private void BtnDownloadClick(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(tbDownloadFileName.Text)) { return; } _ftp.GetFile(tbDownloadFileName.Text, Path.Combine(_directoryDownload, tbDownloadFileName.Text), false); }
/// <summary> /// 下载文件 /// </summary> public void DownloadFile(string localPath, string remotePath, string remoteFile) { try { ftpConnection.GetFile(Combine(remotePath, remoteFile), Path.Combine(localPath, remoteFile), false); } catch { throw; } }
/// <summary> /// 下载 /// </summary> /// <param name="filePath"></param> /// <param name="fileName"></param> public void Download(string filePath, string fileName) { try { conn.GetFile(conn.GetCurrentDirectory() + "/" + fileName, filePath + "\\" + fileName, false); } catch { MessageBox.Show("ftp has lost connection!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void DownloadFile(FtpConnection ftp, FtpFileInfo ftpFileInfo, string remotePath, string localPath) { ConsoleService.WriteToConsole("Downloading " + ftpFileInfo.Name + " (" + FormatHelper.ConvertToHumanReadbleFileSize(ftp.GetFileSize(remotePath + "/" + ftpFileInfo.Name)) + ")"); if (!Directory.Exists(localPath)) { Directory.CreateDirectory(localPath); } var filePath = Path.Combine(localPath, ftpFileInfo.Name); if (File.Exists(filePath)) { File.Delete(filePath); } ftp.GetFile(remotePath + "/" + ftpFileInfo.Name, filePath, false); }
private bool DownloadMapFiles() { int port = _remoteProc.GetFtpPort(); using (var ftp = new FtpConnection(Setting.ServerAddr, port, "anonymous", "password")) { ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory(MapDir); foreach (Map map in _maps) { ftp.GetFile(map.FileName, Path.Combine(MapDir, map.FileName), false); } } return(true); }
public bool FTPTransferHHTToPC(string hostIP, bool checkpermissionMode) { using (FtpConnection ftp = new FtpConnection(hostIP, userFTP, passwordFTP)) { try { ftp.Open(); /* Open the FTP connection */ ftp.Login(userFTP, passwordFTP); /* Login using previously provided credentials */ string remoteFile = ""; string localFile = ""; if (checkpermissionMode) { remoteFile = HHTDBPath + validateDBName; localFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + validateDBName; } else { remoteFile = HHTDBPath + DBName; localFile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + DBName; } if (ftp.FileExists(remoteFile)) /* check that a file exists */ { ftp.GetFile(remoteFile, localFile, false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ return(true); } else { return(false); } } catch (Exception ex) { //Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); log.Error(String.Format("Exception : {0}", ex.StackTrace)); return(false); } } }
public void Execute(IActivityRequest request, IActivityResponse response) { String sourcePath = request.Inputs["Source File Path"].AsString(); String savePath = request.Inputs["Destination File Path"].AsString(); bool overwriteLocal = Convert.ToBoolean(request.Inputs["Overwrite Local File"].AsString()); using (FtpConnection ftp = new FtpConnection(settings.FtpServer, settings.Port, settings.UserName, settings.Password)) { ftp.Open(); ftp.Login(); if (ftp.FileExists(sourcePath)) { ftp.GetFile(sourcePath, savePath, overwriteLocal); } else { response.LogErrorMessage("File does not exist at " + sourcePath); } } }
private void GetFile() { string Newlocation = ""; string ftpusername = "******"; string ftppassword = "******"; string ip = "172.26.50.199"; int FtpPort = Convert.ToInt16("21"); string Actfile = "sample.txt"; int cnt = Actfile.LastIndexOf('.'); string Extn = Actfile.Substring(Actfile.LastIndexOf('.'), Actfile.Length - Actfile.LastIndexOf('.')); using (FtpConnection _ftp = new FtpConnection(ip, FtpPort, ftpusername, ftppassword)) { try { _ftp.Open(); _ftp.Login(); string Ftpfile = "Notifications\\sample.txt"; Newlocation = "D:\\Syed\\Downloaded"; _ftp.GetFile(Ftpfile, Newlocation + "\\" + "sample.txt", false); } catch (FtpException ex) { throw ex; } finally { _ftp.Close(); string strDURL = "D:\\Syed\\Downloaded\\sample.txt"; System.IO.FileInfo toDownload = new System.IO.FileInfo(strDURL); } } }
public static void getFile(ref string UserName, ref string PassWord, ref string ServerName, ref string FileName) { using (FtpConnection ftp = new FtpConnection("ServerName", "UserName", "PassWord")) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ if (ftp.DirectoryExists("/incoming")) /* check that a directory exists */ { ftp.SetCurrentDirectory("/incoming"); /* change current directory */ } if (ftp.FileExists("/incoming/file.txt")) /* check that a file exists */ { ftp.GetFile("/incoming/file.txt", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */ } //do some processing try { ftp.SetCurrentDirectory("/outgoing"); ftp.PutFile(@"c:\localfile.txt", "file.txt"); /* upload c:\localfile.txt to the current ftp directory as file.txt */ } catch (FtpException e) { Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); } foreach (var dir in ftp.GetDirectories("/incoming/processed")) { Console.WriteLine(dir.Name); Console.WriteLine(dir.CreationTime); foreach (var file in dir.GetFiles()) { Console.WriteLine(file.Name); Console.WriteLine(file.LastAccessTime); } } } } // End getFile()
private bool DownloadArquivos(BackgroundWorker status, string pasta, string subpasta) { tamanho = 0; subPastaSelecionada = subpasta; try { if (subpasta.Length > 11 && subpasta.Substring(0, 12).Equals("ScriptsSQL/")) { if (this.DownloadScriptSQLProgressBarControl.InvokeRequired) { DownloadScriptSQLProgressBarControl.Invoke(new MethodInvoker(delegate { this.DownloadScriptSQLProgressBarControl.EditValue = 0; this.DownloadScriptSQLProgressBarControl.Update(); })); } } else if (subpasta.Equals("Sistema")) { if (this.CompSistemaProgressBarControl.InvokeRequired) { CompSistemaProgressBarControl.Invoke(new MethodInvoker(delegate { this.CompSistemaProgressBarControl.EditValue = 0; this.CompSistemaProgressBarControl.Update(); })); } } else if (subpasta.Equals("DevExpress") || subpasta.Equals("postgres/93") || subpasta.Equals("pt-br")) { if (this.CompExternoProgressBarControl.InvokeRequired) { CompExternoProgressBarControl.Invoke(new MethodInvoker(delegate { this.CompExternoProgressBarControl.EditValue = 0; this.CompExternoProgressBarControl.Update(); })); } } if (ftp.DirectoryExists("/" + subpasta)) { ftp.SetCurrentDirectory("/" + subpasta); } var dir = ftp.GetCurrentDirectoryInfo(); tamanho = dir.GetFiles().Length; foreach (var file in dir.GetFiles()) { if (!File.Exists(pasta + file.Name) || subpasta.Equals("ScriptsSQL")) { SetText("[" + file.Name + "]"); ftp.GetFile("/" + subpasta + "/" + file.Name, pasta + file.Name, false); } else { long size = TamanhoArquivoServidor(subpasta, file.Name); FileInfo f = new FileInfo(pasta + file.Name); long size2 = f.Length; //COMPARAR ARQUIVOS DO SERVIDOR/ARQUIVOS LOCAIS if (size != size2) { SetText("[" + file.Name + "]"); ftp.GetFile("/" + subpasta + "/" + file.Name, pasta + file.Name, false); } else { if (subpasta.Length > 11 && subpasta.Substring(0, 12).Equals("ScriptsSQL/")) { DownloadScriptSQLProgressBarControl.Invoke(new MethodInvoker(delegate { this.DownloadScriptSQLProgressBarControl.Properties.Maximum = tamanho; })); } else if (subpasta.Equals("Sistema")) { CompSistemaProgressBarControl.Invoke(new MethodInvoker(delegate { this.CompSistemaProgressBarControl.Properties.Maximum = tamanho; })); } else if (subpasta.Equals("DevExpress") || subpasta.Equals("postgres/93") || subpasta.Equals("pt-br")) { if (this.CompExternoProgressBarControl.InvokeRequired) { CompExternoProgressBarControl.Invoke(new MethodInvoker(delegate { this.CompExternoProgressBarControl.Properties.Maximum = tamanho; })); } } } if (subpasta.Equals("Sistema")) { UpdateBarraArquivosSistema(tamanho); } else if (subpasta.Length > 11 && subpasta.Substring(0, 12).Equals("ScriptsSQL/1")) { UpdateBarraArquivosDownloadScripts(tamanho); } else if (subpasta.Equals("DevExpress") || subpasta.Equals("postgres/93") || subpasta.Equals("pt-br")) { UpdateBarraArquivosExternos(tamanho); } SetText(""); } } } catch { MessageBox.Show("O Sistema identificou que a conexão com o servidor não foi possível. Por favor, tente mais tarde.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } return(true); }
//main operations //download .pdf and print private void ftpOperations() { Int64 fileSize = 0; bool fileProblem = false; using (FtpConnection ftp = new FtpConnection(server.Text, login.Text, password.Text)) { try { ftp.Open(); loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Nawiązuję połączenie..."); })); saveToFile(); //connect to ftp and set remote and local directory ftp.Login(); ftp.SetCurrentDirectory("//" + packingStationNumber); ftp.SetLocalDirectory("C:\\tmp"); } catch (ThreadAbortException) { } catch (Exception e) { loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Błąd połączenia " + e); })); saveToFile(); btnStart.Invoke(new Action(delegate() { btnStart.Enabled = true; })); btnStop.Invoke(new Action(delegate() { btnStop.Enabled = false; })); startOperations.Abort(); } while (true) { btnStart.Invoke(new Action(delegate() { if (btnStart.Enabled == true) { btnStart.Enabled = false; } })); loggingBox.Invoke(new Action(delegate() { if (loggingBox.Items.Count > 2000) { loggingBox.Items.Clear(); } })); try { //search file on ftp foreach (var file in ftp.GetFiles()) { loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Pobieram plik " + file.Name); })); saveToFile(); foreach (var pdfFile in Directory.GetFiles("C:\\tmp")) { if (pdfFile == "C:\\tmp\\" + file.Name) { loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Znalazłem dubla: " + file.Name); })); saveToFile(); fileSize = new FileInfo("C:\\tmp\\" + file.Name).Length; fileProblem = true; } } if (!fileProblem) { ftp.GetFile(file.Name, false); } else if (fileSize > 40000) { MessageBox.Show("Twoja etykieta została pobrana już wcześniej i prawdopodobnie została wysłana. Jej nazwa to " + file.Name, "WARRNING", MessageBoxButtons.OK, MessageBoxIcon.Warning); loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Etykieta już jest na dysku: " + file.Name); })); saveToFile(); fileProblem = true; } else if (fileSize < 40000) { File.Delete("C:\\tmp\\" + file.Name); ftp.GetFile(file.Name, false); loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Etykieta w tmp ma zbyt mały rozmiar: " + file.Name + " i została znowu pobrana"); })); saveToFile(); fileProblem = false; } ftp.RemoveFile(file.Name); if (!fileProblem) { //run program to print .pdf if (sumatra_checkbox.Checked == false) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); FindProgram pdfProgramName = new FindProgram(); startInfo.FileName = (pdfProgramName.findPDFprogram("Adobe") + "\\Reader 11.0\\Reader\\AcroRd32.exe"); startInfo.Arguments = "/s /o /t C:\\tmp\\" + file.Name + " " + printer.Text; process.StartInfo = startInfo; loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Otwieram AR i wywołuję wydruk..."); })); saveToFile(); process.Start(); Thread.Sleep(4000); process.Close(); } else { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); FindProgram pdfProgramName = new FindProgram(); startInfo.FileName = (pdfProgramName.findPDFprogram("SumatraPDF") + "\\SumatraPDF.exe"); startInfo.Arguments = "-silent C:\\tmp\\" + file.Name + " -print-settings fit -print-to " + printer.Text + " -exit-when-done"; process.StartInfo = startInfo; loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Otwieram SumatraPDF i wywołuję wydruk..."); })); saveToFile(); process.Start(); Thread.Sleep(2000); process.Close(); } } fileProblem = false; } } catch (ThreadAbortException) { } catch (Exception e) { loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Błąd przetwarzania plików " + e); })); saveToFile(); loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("Ponowne nawiązanie połączenia"); })); ftp.Close(); ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory("/" + packingStationNumber); ftp.SetLocalDirectory("C:\\tmp"); continue; } Thread.Sleep(750); loggingBox.Invoke(new Action(delegate() { loggingBox.Items.Add("[...]"); })); loggingBox.Invoke(new Action(delegate() { loggingBox.TopIndex = loggingBox.Items.Count - 1; })); } } }