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(".."); }
private void DownloadDirectories(FtpConnection ftp, FtpDirectoryInfo[] dic, string remotePath, string localPath) { foreach (var ftpDirectoryInfo in dic.Where(d => d.Name != "." && d.Name != "..")) { if (_activeConnections < MaxActiveConnections) { _activeConnections++; _downloadTasks.Add(Task.Run(() => { using (FtpConnection ftp2 = GetNewConnection()) { ftp2.Open(); ftp2.Login(); ftp2.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name); DownloadFiles(ftp2, ftp2.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name)); DownloadDirectories(ftp2, ftp2.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name)); } })); } else { ftp.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name); DownloadFiles(ftp, ftp.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name)); DownloadDirectories(ftp, ftp.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name)); } } }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="filedownloadname"></param> /// <param name="dir"></param> /// <returns></returns> public string FtpStream(HttpContext context, string filedownloadname, string dir) { string stream = string.Empty; FtpConnection ftp = this.FtpConn(); ftp.SetCurrentDirectory(dir); //ftp. try { if (ftp.FileExist(filedownloadname)) { FtpStream ftpfs = ftp.OpenFile(filedownloadname, GenericRights.Read); stream = "<"; StreamReader reader = new StreamReader(ftpfs); while (reader.Read() > 0) { stream += reader.ReadToEnd(); } } else { context.Response.Write("<script>alert('file does not exist!');</script>"); } } finally { ftp.Close(); } return(stream); }
public static List <string> GetFileList(string ftpServerName, int ftpPortNumber, string ftpServerUserName, string ftpServerPassWord, string folder, DateTime ReadDate) { var results = new List <string>(); // New FTp client to get modify date string ftpServerNameNewClient = ftpServerName.Split('/').Last(); FtpConnection ftp = new FtpConnection(ftpServerNameNewClient, ftpPortNumber, ftpServerUserName, ftpServerPassWord); ftp.Open(); ftp.Login(); var files = new FtpFileInfo[0]; if (folder != "") { ftp.SetCurrentDirectory(folder); } files = ftp.GetFiles(); foreach (var file in files) { DateTime?lastWriteTime = file.LastWriteTime; if (lastWriteTime != null && lastWriteTime >= ReadDate) { results.Add(file.Name); } } ftp.Close(); return(results); }
private void SendAddOnToServer(List <string> files, String folderPath) { Console.WriteLine("Sending to server"); TextReader tr = new StreamReader(@"C:\Users\Pilus\Documents\Cloud Backup\PrologueServer.txt"); string addr = tr.ReadLine(); string user = tr.ReadLine(); string pass = tr.ReadLine(); using (FtpConnection ftp = new FtpConnection(addr, user, pass)) { ftp.Open(); /* Open the FTP connection */ ftp.Login(); /* Login using previously provided credentials */ int c = 0; int c2 = 0; int transfered = 0; foreach (String file in files) { try { // Check if the directory exists String relativeFilePath = file.Replace(folderPath, "").Replace(@"\", "/"); String totalDirPath = relativeFilePath.Substring(0, relativeFilePath.LastIndexOf("/")); String folder = totalDirPath.Substring(totalDirPath.LastIndexOf("/") + 1); String topDir = "/" + totalDirPath.Replace("/" + folder, ""); if (!ftp.GetCurrentDirectory().Equals("/" + totalDirPath)) { ftp.SetCurrentDirectory(topDir); if (!ftp.DirectoryExists(folder)) { ftp.CreateDirectory(folder); } } if (PutFile(ftp, file) == true) { transfered++; } c++; int c3 = (c / (files.Count / 20)); if (c3 > c2) { Console.Write("{0}% ", c3 * 5); c2 = c3; } } catch (FtpException e) { Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message)); } } Console.WriteLine("{0} files created/updated.", transfered); } }
/// <summary> /// 切换到下级目录,用\\进行目录分割,例如CNC\\FCYA1 /// </summary> /// <param name="sFolderName"></param> public void NextDirectory(string sFolderName) { try { ftpConnection.SetCurrentDirectory(Combine(ftpConnection.GetCurrentDirectory(), sFolderName)); } catch { throw new Exception(string.Format("没有发现对应下级目录{0}, 切换失败!", sFolderName)); } }
/// <summary> /// 切换当前目录 /// </summary> /// <param name="DirectoryName"></param> /// <param name="IsRoot">true 绝对路径 false 相对路径</param> public void GotoDirectory(string DirectoryName, bool IsRoot) { try { conn.SetCurrentDirectory(DirectoryName); } catch { MessageBox.Show("ftp has lost connection!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
void sendCommentClick(object sender, EventArgs e) { try { string localPath = Path.GetTempPath() + "mecomment.dat"; File.WriteAllText(localPath, "\n\n\n\n\n\n\n\n\n\n\n\n" + this.commentBox.Text); ftp.SetCurrentDirectory("/dev_hdd0/home/" + allusers[accLists.SelectedIndex] + "/friendim/"); ftp.PutFile(localPath); MetroMessageBox.Show(this, "Successfully loaded", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } catch { MetroMessageBox.Show(this, "Error couldn't find the folder", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void BtnSetCurrentDirectoryClick(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(tbCurrentDirectory.Text)) { return; } _ftp.SetCurrentDirectory(tbCurrentDirectory.Text); lbDirectories.Items.Clear(); lbFiles.Items.Clear(); }
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()
/// <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)); } } } } }
/// <summary> /// /// </summary> /// <param name="dir"></param> /// <returns></returns> public List <FtpFile> list(string remoteDir) { logger.pushOperation("FTP.list"); List <FtpFile> ret = new List <FtpFile>(); try { try { sFTP.SetCurrentDirectory(remoteDir); } catch (Exception e) { logger.log("Erro: " + e.Message, Logger.LogType.ERROR, e, false); } foreach (FtpFileInfo fi in sFTP.GetFiles()) { FtpFile ftpfile; ftpfile.creationTime = (DateTime)(fi.CreationTime == null? DateTime.Now: fi.CreationTime); ftpfile.extension = fi.Extension; ftpfile.fileName = fi.Name; ret.Add(ftpfile); } } catch (Exception e) { ret = new List <FtpFile>(); logger.log("Erro ao listar arquivos no FTP: " + e.Message, Logger.LogType.ERROR, e, false); } finally { logger.releaseOperation(); } return(ret); }
public void ClearFtp(FtpConnection ftp, string directory) { ftp.SetCurrentDirectory(directory); var dirs = ftp.GetDirectories(); foreach (var dir in dirs) { if ((dir.Name != ".") && (dir.Name != "..")) { ClearFtp(ftp, dir.Name); //Recursive call ftp.RemoveDirectory(dir.Name); } } foreach (var file in ftp.GetFiles()) { ftp.RemoveFile(file.Name); } if (ftp.GetCurrentDirectory() != "/") { ftp.SetCurrentDirectory(".."); } }
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 void PublishToGitFTP(DeploymentModel model) { if (model.AzureDeployment) { var remoteProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" remote add blog " + model.AzureRepo); if (remoteProcess != null) { remoteProcess.WaitForExit(); } var pushProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" push -f blog master"); if (pushProcess != null) { pushProcess.WaitForExit(); } } else { using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword)) { try { ftp.Open(); ftp.Login(); if (!string.IsNullOrWhiteSpace(model.FTPPath)) { if (!ftp.DirectoryExists(model.FTPPath)) { ftp.CreateDirectory(model.FTPPath); } ftp.SetCurrentDirectory(model.FTPPath); } FtpBlogFiles(snowPublishPath, model.FTPPath); } catch (Exception ex) { } } } }
public void StartFTP() { string msg = string.Empty; if (dataBase_.dtSettlePrice.Rows.Count > 0) { if (File.Exists(ftpFileName_)) { File.Delete(ftpFileName_); } using (FtpConnection ftp = new FtpConnection(ftpIP_, ftpID_, ftpPassword_)) { using (StreamWriter streamWriter = new StreamWriter(ftpFileName_, false)) { foreach (DataRow item in dataBase_.dtSettlePrice.Rows) { streamWriter.WriteLine(string.Format("{0,-16}{1,-6} {2:000000.000000} ", item["Pid"], item["YM"], item["SettlePrice"])); } streamWriter.Flush(); } ftp.Open(); ftp.Login(); try { ftp.SetCurrentDirectory(ftpDirectory_); ftp.PutFile(ftpFileName_, ftpFileName_); msg = string.Format("{0}\t{1}:{2},Finish FTP Closing to {3}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } catch (FtpException ex) { msg = String.Format("{0}\t{1}:{2}, Exception ErrCode: {3}, Message: {4}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.ErrorCode, ex.Message); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } } } else { msg = string.Format("{0}\t{1}:{2},本日無資料 !", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_); srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg)); } }
static void Main(string[] args) { string error = ""; try { error = "host error"; string host = args[0]; error = "localPath error"; string localFilePath = args[1]; error = "serverPath error"; string serverFilePath = args[2]; error = "error connecting.."; using (FtpConnection ftp = new FtpConnection(host)) { if (!ftp.IsConnected) { Console.WriteLine(error); } error = "error moving file..!"; string fileName = serverFilePath.Contains("/") ? serverFilePath.Substring(serverFilePath.LastIndexOf('/')).Replace("/", "").Replace("//", "") : serverFilePath; string dirPath = serverFilePath.Contains("/") ? serverFilePath.Substring(0, serverFilePath.LastIndexOf('/')) + '/' : "dev_hdd0/"; ftp.SetCurrentDirectory(dirPath); ftp.PutFile(localFilePath, fileName); foreach (var item in ftp.GetFiles()) { if (item.FullName == fileName) { Console.WriteLine("success :\nsource( {0} )\ndestination( {1} )", localFilePath, dirPath + fileName); MessageBeep(0); break; } } } } catch { Console.WriteLine(error); MessageBeep(16); Console.Read(); } }
// Function to store ftp public bool s2FTP(String url, String name) { using (FtpConnection ftp = new FtpConnection("127.0.0.1", "rahul", "rahul")) {; /* Open the FTP connection */ ftp.Open(); /* Login using previously provided credentials */ ftp.Login(); try { ftp.SetCurrentDirectory("/"); ftp.PutFile(@url, name); /* 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)); } } return(true); }
/// <summary> /// Upload Files /// </summary> private void UploadFiles() { if (this.FileNames == null) { this.Log.LogError("The required fileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { this.LogTaskMessage("Uploading Files"); if (!string.IsNullOrEmpty(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)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { if (File.Exists(fileName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName)); ftpConnection.PutFile(fileName); } } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } }
private bool PutFile(FtpConnection ftp, string file) { string ftpPart = file.Remove(0, file.IndexOf(@"Interface\AddOns\") + (@"Interface\AddOns\").Length); string folderName = ftpPart.Remove(ftpPart.LastIndexOf(@"\")); string fileName = ftpPart.Remove(0, ftpPart.LastIndexOf(@"\") + 1); if (!currentDir.Equals(folderName)) { ftp.SetCurrentDirectory(@"\" + folderName); currentDir = folderName; currentDirFileInfo = ftp.GetFiles(); } FileInfo localFileInfo = new FileInfo(file); FtpFileInfo ftpFileInfo = null; foreach (FtpFileInfo info in currentDirFileInfo) { if (info.Name.Equals(fileName)) { ftpFileInfo = info; } } if (ftpFileInfo == null) { ftp.PutFile(file, fileName); return(true); } else { DateTime ftpTime = ftpFileInfo.LastWriteTimeUtc ?? DateTime.MinValue; if (ftpTime < localFileInfo.LastWriteTimeUtc) { ftp.PutFile(file, fileName); return(true); } } return(false); }
private static void DownloadFiles(ServerInfo server) { string tempFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "MapUpdater"; ConnectionInfo connection = server.MinecraftConnection; if (connection.Type == ConnectionType.Ftp) { using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password)) { ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory(connection.WorldsFolder); if (ftp.GetCurrentDirectory() != connection.WorldsFolder) { Console.WriteLine("WorldsFolder does not exist on server"); } DownloadDirectory(ftp, server.World.Name, tempFolder + Path.DirectorySeparatorChar + server.World.Name); } } }
private void FtpBlogFiles(string dirPath, string uploadPath) { string[] files = Directory.GetFiles(dirPath, "*.*"); string[] subDirs = Directory.GetDirectories(dirPath); foreach (string file in files) { ftp.PutFile(file, Path.GetFileName(file)); } foreach (string subDir in subDirs) { if (!ftp.DirectoryExists(uploadPath + "/" + Path.GetFileName(subDir))) { ftp.CreateDirectory(uploadPath + "/" + Path.GetFileName(subDir)); } ftp.SetCurrentDirectory(uploadPath + "/" + Path.GetFileName(subDir)); FtpBlogFiles(subDir, uploadPath + "/" + Path.GetFileName(subDir)); } }
/// <summary> /// Delete given files from the FTP Directory /// </summary> private void DeleteFiles() { if (this.FileNames == null) { this.Log.LogError("The required FileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { ftpConnection.LogOn(); this.LogTaskMessage("Deleting Files"); if (!string.IsNullOrEmpty(this.RemoteDirectoryName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting: {0}", fileName)); ftpConnection.DeleteFile(fileName); } catch (FtpException ex) { if (ex.Message.Contains("550")) { continue; } this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error in deleting file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } }
private static void UploadMapImages(ServerInfo server) { string currentDirectory = Environment.CurrentDirectory; ConnectionInfo connection = server.WebConnection; if (connection.Type == ConnectionType.Ftp) { using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password)) { ftp.Open(); ftp.Login(); ftp.SetCurrentDirectory(connection.ImagesFolder); if (ftp.GetCurrentDirectory() != connection.ImagesFolder) { Console.WriteLine("ImagesFolder does not exist on server"); } foreach (string file in Directory.GetFiles(Environment.CurrentDirectory, "*.png")) { ftp.PutFile(file); } } } }
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; })); } } }
public void PublishToGitFTP(DeploymentModel model) { if (model.GitDeployment) { Logger.Debug("Executing git add"); var addProcess = new Process(); var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A" }; addProcess.StartInfo = addProcessStartInfo; addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); addProcess.Start(); addProcess.BeginOutputReadLine(); addProcess.BeginErrorReadLine(); addProcess.WaitForExit(); Logger.Debug("git add process to exited"); Logger.Debug("Executing git email config process"); var emailProcess = new Process(); var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\"" }; emailProcess.StartInfo = emailProcessStartInfo; emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); emailProcess.Start(); emailProcess.BeginOutputReadLine(); emailProcess.BeginErrorReadLine(); emailProcess.WaitForExit(); Logger.Debug("git email config process to exited"); Logger.Debug("Executing git name config process"); var userProcess = new Process(); var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\"" }; userProcess.StartInfo = userProcessStartInfo; userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); userProcess.Start(); userProcess.BeginOutputReadLine(); userProcess.BeginErrorReadLine(); userProcess.WaitForExit(); Logger.Debug("git name config process to exited"); Logger.Debug("Executing git commit"); var commitProcess = new Process(); var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" commit -a -m \"Static Content Regenerated\"" }; commitProcess.StartInfo = commitProcessStartInfo; commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); commitProcess.Start(); commitProcess.BeginOutputReadLine(); commitProcess.BeginErrorReadLine(); commitProcess.WaitForExit(); Logger.Debug("git commit process to exited"); Logger.Debug("Executing git push"); var pushProcess = new Process(); var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"") { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master" }; pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data); pushProcess.StartInfo = pushProcessStartInfo; pushProcess.Start(); pushProcess.BeginOutputReadLine(); pushProcess.BeginErrorReadLine(); pushProcess.WaitForExit(); Logger.Debug("git push process to exited"); } else { using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword)) { try { ftp.Open(); ftp.Login(); if (!string.IsNullOrWhiteSpace(model.FTPPath)) { var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/')); /* Get name of the directory */ var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower(); /* Get all child directories info of the parent directory */ var ftpDirectories = ftp.GetDirectories(parrentDirectory); /* check if the given directory exists in the returned result */ var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory); if (!exists) { ftp.CreateDirectory(model.FTPPath); } ftp.SetCurrentDirectory(model.FTPPath); } FtpBlogFiles(publishGitPath, model.FTPPath); } catch (Exception ex) { } } } }
/// <summary> /// Upload Files /// </summary> private void UploadFiles() { if (this.FileNames == null) { this.Log.LogError("The required fileNames attribute has not been set for FTP."); return; } using (FtpConnection ftpConnection = this.CreateFtpConnection()) { this.LogTaskMessage("Uploading Files"); if (!string.IsNullOrEmpty(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)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName)); ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName); } var overwrite = true; var files = new List <FtpFileInfo>(); if (!string.IsNullOrEmpty(this.Overwrite)) { if (!bool.TryParse(this.Overwrite, out overwrite)) { overwrite = true; } } if (!overwrite) { files.AddRange(ftpConnection.GetFiles()); } foreach (string fileName in this.FileNames.Select(item => item.ItemSpec)) { try { if (File.Exists(fileName)) { if (!overwrite && files.FirstOrDefault(fi => fi.Name == fileName) != null) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Skipped: {0}", fileName)); continue; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName)); ftpConnection.PutFile(fileName); } } catch (FtpException ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode)); } } } }
public void SetCurrentDirectory(string directory) { _ftpConnection.SetCurrentDirectory(directory); }
private ActionResult FtpUpload(IJob job) { var actionResult = Check(job.Profile); if (!actionResult) { Logger.Error("Canceled FTP upload action."); return(actionResult); } if (string.IsNullOrEmpty(job.Passwords.FtpPassword)) { Logger.Error("No ftp password specified in action"); return(new ActionResult(ActionId, 102)); } Logger.Debug("Creating ftp connection.\r\nServer: " + job.Profile.Ftp.Server + "\r\nUsername: "******"Can not connect to the internet for login to ftp. Win32Exception Message:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 108)); } Logger.Error("Win32Exception while login to ftp server:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 104)); } catch (Exception ex) { Logger.Error("Exception while login to ftp server:\r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 104)); } var fullDirectory = job.TokenReplacer.ReplaceTokens(job.Profile.Ftp.Directory).Trim(); if (!IsValidPath(fullDirectory)) { Logger.Warn("Directory contains invalid characters \"" + fullDirectory + "\""); fullDirectory = MakeValidPath(fullDirectory); } Logger.Debug("Directory on ftp server: " + fullDirectory); var directories = fullDirectory.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries); try { foreach (var directory in directories) { if (!ftp.DirectoryExists(directory)) { Logger.Debug("Create folder: " + directory); ftp.CreateDirectory(directory); } Logger.Debug("Move to: " + directory); ftp.SetCurrentDirectory(directory); } } catch (Exception ex) { Logger.Error("Exception while setting directory on ftp server\r\n:" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 105)); } var addendum = ""; if (job.Profile.Ftp.EnsureUniqueFilenames) { Logger.Debug("Generate addendum for unique filename"); try { addendum = AddendumForUniqueFilename(Path.GetFileName(job.OutputFiles[0]), ftp); Logger.Debug("The addendum for unique filename is \"" + addendum + "\" If empty, the file was already unique."); } catch (Exception ex) { Logger.Error("Exception while generating unique filename\r\n:" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 106)); } } foreach (var file in job.OutputFiles) { try { var targetFile = Path.GetFileNameWithoutExtension(file) + addendum + Path.GetExtension(file); ftp.PutFile(file, MakeValidPath(targetFile)); } catch (Exception ex) { Logger.Error("Exception while uploading the file \"" + file + "\": \r\n" + ex.Message); ftp.Close(); return(new ActionResult(ActionId, 107)); } } ftp.Close(); return(new ActionResult()); }