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> /// 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()); } }
/// <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> /// 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> /// 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(); } }
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; } } }