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 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 DownFiles(FtpConnection connection) { try { connection.ChDir("PDA"); string[] files = connection.GetFiles(); if (null != files && files.Length > 0) { var app_dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); for (int i = 0; i < files.Length; i++) { connection.DownloadFile(files[i], app_dir + "\\" + files[i]); } Console.WriteLine("download complete"); } else { Console.WriteLine("the directory has any file"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { connection.Close(); } }
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)); } } }
private void BtnGetFilesClick(object sender, EventArgs e) { FtpFileInfo[] ftpFileInfos = _ftp.GetFiles(); lbFiles.Items.Clear(); lbFiles.Items.AddRange(ftpFileInfos.OrderBy(fi => fi.Name).Select(fi => (object)fi.Name).ToArray()); }
/// <summary> /// 获取目录下的directory 和files /// </summary> /// <returns></returns> public String[] getAllFiles() { StringBuilder result = new StringBuilder(); try { foreach (var dir in conn.GetDirectories(conn.GetCurrentDirectory())) { result .Append(dir.Attributes.ToString()).Append("?") .Append(dir.Name).Append("?") .Append("0").Append("?") .Append(dir.LastWriteTime).Append("?") .Append("\n"); } foreach (var f in conn.GetFiles(conn.GetCurrentDirectory())) { result .Append(f.Attributes).Append("?") .Append(f.Name).Append("?") .Append(conn.GetFileSize(conn.GetCurrentDirectory() + "/" + f.Name)).Append("?") .Append(f.LastWriteTime).Append("?") .Append("\n"); } } catch { MessageBox.Show("ftp has lost connection!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(result.ToString().Split('\n')); }
public static FtpFileInfo[] GetFiles(string path) { FtpConnection conn = GetFtpConnection(); conn.Open(); conn.Login(); FtpFileInfo[] files = conn.GetFiles(path); conn.Close(); conn.Dispose(); return(files); }
/// <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> public virtual string[] GetFileList(string LocaPath) { try { var result = new List <string>(); ftpConnection.GetFiles(LocaPath).ToList().ForEach(u => { result.Add(u.Name); }); return(result.ToArray()); } catch { throw; } }
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(); } }
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); }
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(".."); } }
/// <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); }
/// <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)); } } } }
//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; })); } } }