private static void backup(FTPClient ftp, DirectoryInfo dir, Regex regex, RegistryKey key) { string[] files = ftp.Dir(null, true); string[] names = new string[files.Length]; int i = 0; foreach (string file in files) { names[i] = file.Substring(56); if (file.Substring(0,1) == "d") { // A directory! if (dir.GetDirectories(names[i]).Length != 1 && !names[i].Substring(0,1).Equals(".")) RecRm(ftp, names[i]); } else // A file! if (regex.IsMatch(names[i]) && dir.GetFiles(names[i]).Length != 1) ftp.Delete(names[i]); i++; } foreach (DirectoryInfo subdir in dir.GetDirectories()) { if (!stringSearch(names, subdir.Name)) ftp.MkDir(subdir.Name); ftp.ChDir(subdir.Name); backup(ftp, subdir, regex, getDataKey(ref key, subdir.Name)); ftp.ChDir(".."); } foreach (FileInfo file in dir.GetFiles()) { if (!regex.IsMatch(file.Name)) continue; if (file.LastWriteTime > getDateTime(key.GetValue(file.Name, "0001-01-01 00:00:00").ToString())) { ftp.Put(file.FullName, file.Name, false); key.SetValue(file.Name, DateTime.Now.ToString()); } } }
public bool Put(Photo ph) { //функция отправки одной фотки (какой - в аргументах вызова) на сервер //lock (lock_) bool f = true; if(ph!=null) if (ph.name.Length>=32) try { ph.name = ph.name.Substring(32); string filepath = "photos" + "/" + ph.name.ToString().Substring(0, 1) + "/" + ph.name.ToString().Substring(1, 1) + "/"; //File.WriteAllBytes("photos" + "/" + ph.name, ph.photo); //Console.WriteLine("Ищем путь " + "photos" + "/" + sb.ToString().Substring(0, 1) + "/" +sb.ToString().Substring(1, 1) + "/"); if (Directory.Exists(filepath)) { try { //Console.WriteLine("Отправляем через sshfs"); if (!File.Exists(filepath + ph.name)) File.WriteAllBytes(filepath + ph.name, ph.photo); /*else Console.WriteLine("не отсылаем фото, т.к. оно уже на сервере");*/ } catch (Exception exx) { string s = exx.Message; if (!s.Contains("553")) ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, ph.name, "Ошибка отправки фоток-2: " + s); Console.WriteLine("Ошибка отправки фоток-2: " + s); } } else { FTPClient conn = new FTPClient("srv5.r-slon.com"); if (conn != null) { try { conn.Login("gsmcity", "fZZ9PQ1DnN"); conn.TransferType = FTPTransferType.BINARY; conn.CloseStreamsAfterTransfer = true; if (!conn.IsConnected) conn.Connect(); filepath = filepath.Replace("photos/", ""); if(!conn.Exists(filepath + ph.name)) conn.Put(ph.photo, filepath + ph.name); /*else Console.WriteLine("не отсылаем фото, т.к. оно уже на сервере");*/ } catch(Exception exx) { string s = exx.Message; if(!s.Contains("553")) ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, ph.name, "Ошибка отправки фоток-0-1: " + s); Console.WriteLine("Ошибка отправки фоток-0-1: " + s); } finally { conn.Quit(); GC.SuppressFinalize(conn); } } else ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, ph.name, "Ошибка отправки фоток-0: не создалось ftp-подключение"); } } catch (Exception ex) { string s = ex.Message; if (!(s.Contains("553") || s.Contains("530"))) f = false; ddbs.WriteErrorMessage(ddbs.ConnectionString, 0, ph.name, "Ошибка отправки фоток-1: " + s); //return false; } return f; }
/// <summary> /// Attempts to connect to the remote location. /// </summary> public void Connect() { // Init FTP client _ftp = new FTPClient(_settings.Address, _settings.Port); _ftp.CommandSent += new FTPMessageHandler(Ftp_CommandSent); _ftp.ReplyReceived += new FTPMessageHandler(Ftp_ReplyReceived); _ftp.BytesTransferred += new BytesTransferredHandler(Ftp_BytesTransferred); _ftp.Login(_settings.Login, _settings.Password); _ftp.TransferType = FTPTransferType.BINARY; // Setup root deploy path string rootpath = _ftp.Pwd(); _remoteRootPath = Path.Combine(rootpath, _settings.Path.TrimStart('\\', '/')); _currentRemotePath = null; }
/// <summary> /// Loads data from the server into the text box. /// </summary> private void LoadData() { try { FTPClient client = new FTPClient(); client.RemoteHost = this.textBoxHost.Text; client.Connect(); client.Login(this.textBoxUser.Text, this.maskedTextBoxPass.Text); this.textBoxStudents.Text = Encoding.UTF8.GetString(client.Get(this.textBoxPath.Text)); this.textBoxStudents.Enabled = true; client.Quit(); } catch (Exception ex) { this.textBoxStudents.Enabled = false; MessageBox.Show(ex.ToString()); } }
private static void RecRm(FTPClient ftp, string name) { ftp.ChDir(name); string[] list; if ((list = ftp.Dir(null, true)).Length > 0) { foreach (string thing in list) { string thingname = thing.Substring(56); if (thing.Substring(0,1) == "d") RecRm(ftp, thingname); else ftp.Delete(thingname); } } ftp.ChDir(".."); ftp.RmDir(name); }
/// <summary> /// Test harness /// </summary> public static void Main(string[] args) { // we want remote host, user name and password if (args.Length < 7) { log.Debug(Convert.ToString(args.Length)); Usage(); System.Environment.Exit(1); } try { // assign args to make it clear string host = args[0]; string user = args[1]; string password = args[2]; string filename = args[3]; string directory = args[4]; string mode = args[5]; string connMode = args[6]; FTPClient ftp = new FTPClient(); ftp.RemoteHost = host; ftp.ControlPort = 21; // set up message collector ftp.CommandSent += new FTPMessageHandler(FTPClientTest.LogCommand); ftp.ReplyReceived += new FTPMessageHandler(FTPClientTest.LogReply); ftp.TransferStarted += new EventHandler(FTPClientTest.LogTransferStarted); ftp.TransferComplete += new EventHandler(FTPClientTest.LogTransferComplete); // connect ftp.Connect(); ftp.Login(user, password); ftp.Quit(); // connect again ftp = new FTPClient(host); ftp.CommandSent += new FTPMessageHandler(FTPClientTest.LogCommand); ftp.ReplyReceived += new FTPMessageHandler(FTPClientTest.LogReply); ftp.TransferStarted += new EventHandler(FTPClientTest.LogTransferStarted); ftp.TransferComplete += new EventHandler(FTPClientTest.LogTransferComplete); ftp.BytesTransferred += new BytesTransferredHandler(FTPClientTest.BytesTransferred); ftp.Login(user, password); // binary transfer if (mode.ToUpper().Equals("BINARY".ToUpper())) { ftp.TransferType = FTPTransferType.BINARY; } else if (mode.ToUpper().Equals("ASCII".ToUpper())) { ftp.TransferType = FTPTransferType.ASCII; } else { log.Debug("Unknown transfer type: " + args[5]); System.Environment.Exit(- 1); } // PASV or active? if (connMode.ToUpper().Equals("PASV".ToUpper())) { ftp.ConnectMode = FTPConnectMode.PASV; } else if (connMode.ToUpper().Equals("ACTIVE".ToUpper())) { ftp.ConnectMode = FTPConnectMode.ACTIVE; } else { log.Debug("Unknown connect mode: " + args[6]); System.Environment.Exit(- 1); } // change dir ftp.ChDir(directory); // Put a local file to remote host ftp.Put(filename, filename); // get bytes byte[] buf1 = ftp.Get(filename); log.Debug("Got " + buf1.Length + " bytes"); // append local file try { ftp.Put(filename, filename, true); } catch (FTPException ex) { log.Debug("Append failed: " + ex.Message); } // get bytes again - should be 2 x //byte[] buf2 = ftp.Get(filename); //log.Debug("Got " + buf2.Length + " bytes"); // rename ftp.Rename(filename, filename + ".new"); // get a remote file - the renamed one ftp.Get(filename + ".tst", filename + ".new"); // delete the remote file ftp.Delete(filename + ".new"); // ASCII transfer ftp.TransferType = FTPTransferType.ASCII; // test that dir() works in full mode string[] listings = ftp.Dir(".", true); for (int i = 0; i < listings.Length; i++) log.Debug(listings[i]); // and now DirDetails test FTPFile[] files = ftp.DirDetails("."); log.Debug(files.Length + " files"); for (int i = 0; i < files.Length; i++) { log.Debug(files[i].ToString()); } // try system() log.Debug(ftp.GetSystem()); // try pwd() log.Debug(ftp.Pwd()); ftp.Quit(); log.Debug("******** message log ********"); log.Debug(FTPClientTest.messages.ToString()); } catch (SystemException ex) { log.Debug("Caught exception: " + ex.Message); } catch (FTPException ex) { log.Debug("Caught exception: " + ex.Message); } }
/// <summary> /// Disconnects from the remote location. /// </summary> public void Disconnect() { _ftp.Quit(); _ftp = null; }
/// <summary> /// Checks if we have a idle connection to the remote ftp server /// </summary> /// <param name="hostname">hostname or ipadres of the ftp server</param> /// <param name="login">loginname</param> /// <param name="password">password</param> /// <param name="port">tcp/ip port</param> /// <param name="ftpclient">on return contains the idle ftp connection for this server /// or null if none is found</param> /// <returns> /// true: found an idle connection, this is returned in ftpclient /// false: no idle connections found. ftpclient =null /// </returns> public static bool InCache(string hostname, string login, string password, int port, bool active, out FTPClient ftpclient) { ftpclient = null; foreach (FtpConnection client in ftpConnections) { if (client.HostName == hostname && client.LoginName == login && client.Password == password && client.Port == port) { if (!client.Busy) { ftpclient = client.Connection; return true; } } } return false; }
/// <summary>Close a connection to a server</summary> public void Close() { if (IsConnected) { //throw new FTPTaskException("Connection is already closed"); _task.Log(Level.Info, "Disconnecting from '{0}'", Server); _client.Quit(); _client = null; _task = null; } return; }
/// <summary> /// Loads the student names from the remote server into the program. /// </summary> private void LoadNames() { try { FTPClient client = new FTPClient(); client.RemoteHost = Settings.Default.DefaultFtpHost; client.Connect(); client.Login(Settings.Default.DefaultFtpUserName, Settings.Default.DefaultFtpPassword); this.names.Clear(); this.names.AddRange(Encoding.UTF8.GetString(client.Get(Settings.Default.DefaultFtpPath)).Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)); } catch (Exception e) { new ThreadExceptionDialog(e).ShowDialog(); } }
protected internal FTPConnection(FTPClient ftpClient) { this.components = null; this.log = Logger.GetLogger("FTPConnection"); this.clientLock = new object(); this.useAutoLogin = true; this.areEventsEnabled = true; this.isTransferringData = false; this.guiControl = null; this.haveQueriedForControl = false; this.currentFileSize = -1L; this.useGuiThread = true; this.localDir = null; this.remoteDir = null; this.lastTransferCancel = false; lock (instanceCountMutex) { this.instanceNumber = instanceCount++; } this.ftpClient = ftpClient; this.activeClient = ftpClient; this.ftpClient.AutoPassiveIPSubstitution = true; this.ftpClient.BytesTransferred += new BytesTransferredHandler(this.ftpClient_BytesTransferred); this.fileTransferType = FTPTransferType.BINARY; ftpClient.CommandSent += new FTPMessageHandler(this.ftpClient_CommandSent); ftpClient.ReplyReceived += new FTPMessageHandler(this.ftpClient_ReplyReceived); ftpClient.ActivePortRange.PropertyChangeHandler = new PropertyChangedEventHandler(this.OnActivePortRangeChanged); ftpClient.FileNotFoundMessages.PropertyChangeHandler = new PropertyChangedEventHandler(this.OnFileNotFoundMessagesChanged); ftpClient.TransferCompleteMessages.PropertyChangeHandler = new PropertyChangedEventHandler(this.OnFileNotFoundMessagesChanged); ftpClient.DirectoryEmptyMessages.PropertyChangeHandler = new PropertyChangedEventHandler(this.OnDirectoryEmptyMessagesChanged); }
public void Ftp(List<string> zipFiles) { IEnumerable<XElement> ftps = gConfig.GetElements("Backup/Ftp"); foreach (XElement xeFtp in ftps) { if (gAbortTask) break; string ftpServer = xeFtp.zAttribValue("server"); if (ftpServer == null) { //cTrace.Trace("Ftp : server is'nt defined"); gTaskTrace.WriteLine("Ftp : server is'nt defined"); continue; } string ftpUser = xeFtp.zAttribValue("user"); if (ftpUser == null) { //cTrace.Trace("Ftp : user is'nt defined"); gTaskTrace.WriteLine("Ftp : user is'nt defined"); continue; } string ftpPassword = xeFtp.zAttribValue("password"); string ftpDirectory = xeFtp.zAttribValue("directory"); string dir = ""; if (ftpDirectory != null) dir = " directory " + ftpDirectory; gTaskTrace.WriteLine("Ftp : connect to server {0}{1}", ftpServer, dir); FTPClient ftp = new FTPClient(); try { ftp.RemoteHost = ftpServer; ftp.Connect(); ftp.Login(ftpUser, ftpPassword); if (ftpDirectory != null) ftp.ChDir(ftpDirectory); ftp.TransferType = FTPTransferType.BINARY; ftp.BytesTransferred += new BytesTransferredHandler(FtpBytesTransferred); int iFile = 0; foreach (string zipFile in zipFiles) { if (gAbortTask) break; gTaskProgress.SetProgressText("Ftp copy file " + zipFile); gTaskProgress.SetProgress(++iFile, zipFiles.Count); gTaskTrace.WriteLine("Ftp : copy file {0}", zipFile); if (!zFile.Exists(zipFile)) { //cTrace.Trace("Ftp : file does'nt exist {0}", zipFile); gTaskTrace.WriteLine("Ftp : file does'nt exist {0}", zipFile); continue; } string remoteFile = zPath.GetFileName(zipFile); //glFtpByteToTransfer = new FileInfo(zipFile).Length; glFtpByteToTransfer = zFile.CreateFileInfo(zipFile).Length; gTaskProgressDetail.SetProgressText("FTP transfer file {0}", remoteFile); try { ftp.Put(zipFile, remoteFile); } catch { if (!gbErrorGeneratedByFtpStop) throw; //string sError = cError.GetErrorMessage(ex, false, true); //gTrace.Trace(sError); break; } gTaskProgressDetail.SetProgress(glFtpByteToTransfer, glFtpByteToTransfer); } ftp.BytesTransferred -= new BytesTransferredHandler(FtpBytesTransferred); } finally { if (!gbErrorGeneratedByFtpStop) ftp.Quit(); else gbErrorGeneratedByFtpStop = false; } } }
/// <summary> /// Start downloading a file from a remote server to local harddisk /// orgremoteFile is in format remote:hostname?port?login?password?folder /// while the remotefile only contains the remote path+filename /// </summary> /// <param name="ftpclient">FTP client to use</param> /// <param name="orgremoteFile">remote file including all details</param> /// <param name="remotefile">remote file including only path+filename</param> /// <param name="localfile">filename where download should be stored</param> /// <returns> /// true: download is started /// false: unable to download file /// </returns> public static bool Download(FTPClient ftpclient, string orgremoteFile, string remotefile, string localfile) { foreach (FtpConnection client in ftpConnections) { if (client.Connection == ftpclient) { if (!client.Busy) { client.Busy = true; client.Download(orgremoteFile, remotefile, localfile); return true; } } } return false; }
/// <summary> /// Remove an ftp client from the cache /// this can be used to remove ftp clients which are disconnected /// </summary> /// <param name="ftpclient">FTPClient</param> public static void Remove(FTPClient ftpclient) { foreach (FtpConnection client in ftpConnections) { if (client.Connection == ftpclient) { ftpConnections.Remove(client); return; } } }
private static void sync(object sender, EventArgs e) { RegistryKey key = getDataKey(); FTPClient ftp = null; DirectoryInfo dir = new DirectoryInfo(props.Folder); Regex regex = new Regex(props.Regex); try { systray.Text = "bakkappah - connecting..."; ftp = new FTPClient(props.Server, props.Port, 30000); ftp.Login(props.User, props.Password); ftp.ConnectMode = FTPConnectMode.ACTIVE; ftp.TransferType = FTPTransferType.BINARY; systray.Text = "bakkappah - uploading..."; backup(ftp, dir, regex, key); } catch { return; } finally { try { ftp.Quit(); } catch {} systray.Text = "bakkappah"; } }
/// <summary> /// Saves data from the text box onto the server. /// </summary> private void SaveData() { try { FTPClient client = new FTPClient(); client.RemoteHost = this.textBoxHost.Text; client.Connect(); client.Login(this.textBoxUser.Text, this.maskedTextBoxPass.Text); client.Put(Encoding.UTF8.GetBytes(this.textBoxStudents.Text), this.textBoxPath.Text); client.Quit(); this.DialogResult = DialogResult.OK; this.Close(); } catch (Exception ex) { this.textBoxStudents.Enabled = false; if (MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OKCancel) == DialogResult.OK) { this.Close(); } } }
/// <summary> /// Create an FTPConnection using the given FTP client. /// </summary> /// <param name="ftpClient"><see cref="FTPClient"/>-instance to use.</param> protected internal FTPConnection(FTPClient ftpClient) { log.Info(VersionDetails.GetVersionDetails(this.GetType())); log.Info("Built: " + BuildTimestamp); lock (instanceCountMutex) { this.instanceNumber = instanceCount++; } this.ftpClient = ftpClient; this.activeClient = ftpClient; this.ftpClient.AutoPassiveIPSubstitution = true; this.ftpClient.BytesTransferred += new BytesTransferredHandler(ftpClient_BytesTransferred); fileTransferType = FTPTransferType.BINARY; ftpClient.CommandSent += new FTPMessageHandler(ftpClient_CommandSent); ftpClient.ReplyReceived += new FTPMessageHandler(ftpClient_ReplyReceived); ftpClient.CommandError += new FTPErrorEventHandler(ftpClient_CommandError); ftpClient.ActivePortRange.PropertyChangeHandler = new PropertyChangedEventHandler(OnActivePortRangeChanged); ftpClient.FileNotFoundMessages.PropertyChangeHandler = new PropertyChangedEventHandler(OnFileNotFoundMessagesChanged); ftpClient.TransferCompleteMessages.PropertyChangeHandler = new PropertyChangedEventHandler(OnFileNotFoundMessagesChanged); ftpClient.DirectoryEmptyMessages.PropertyChangeHandler = new PropertyChangedEventHandler(OnDirectoryEmptyMessagesChanged); }
/// <summary>Open a connection to the specified server.</summary> /// <param name="task">The task using this connection</param> public void Open(FTPTask task) { if (_task!=null) { throw new FTPTaskException("This connection is already being used by "+_task.ToString()); } if (task==null) { throw new FTPTaskException("Must specify the task that will use this connection."); } _task = task; if (IsConnected) { throw new FTPTaskException("This connection is already open."); } _task.Log(Level.Info, "Using '{0}':", ID); // ensure this connection object has all the info it needs Validate(); if (!_task.Exec) { _task.Log(Level.Info, "-------------- Debugging the ftp queries --------------"); _task.Log(Level.Info, "Connection will be attempted to scan remotely for <get> sets"); _task.Log(Level.Info, "but no transfers will be attempted in either direction"); _task.Log(Level.Info, "and neither local nor remote file trees will be modified."); _task.Log(Level.Info, "-------------------------------------------------------\n"); } _task.Log(Level.Info, "Connecting to '{0}' as '{1}' . . .", Server, UserName); _task.Log(Level.Verbose, "Instantiating the FTPClient & opening the connection..."); _client = new FTPClient(Server); _task.Log(Level.Verbose, "Authenticating..."); Login(UserName, Password); _task.Log(Level.Verbose, "and setting the connection mode to passive."); _client.ConnectMode = ParseConnectMode(ParseConnectMode(_task.ConnectMode)); return; }
private void _test_Click(object sender, EventArgs e) { try { this.Cursor = Cursors.WaitCursor; FTPClient ftp = new FTPClient(_address.Text, int.Parse(_port.Text)); ftp.Login(_login.Text, _password.Text); ftp.Quit(); MessageBox.Show("The connection was successfully established.", "Connection successful", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } this.Cursor = Cursors.Default; }