/// <summary> /// 连接FTP /// </summary> /// <returns></returns> public bool Connect() { bool result = false; if (ftpClient != null) { if (ftpClient.IsConnected) { Log4netUtil.Log4NetHelper.Info(String.Format(@"Connect->连接FTP成功:{0}", string.Empty), @"Ftp"); return(true); } else { try { ftpClient.Connect(); Log4netUtil.Log4NetHelper.Info(String.Format(@"Connect->连接FTP成功:{0}", string.Empty), @"Ftp"); return(true); } catch (Exception ex) { Log4netUtil.Log4NetHelper.Error(String.Format(@"Connect->连接FTP异常:{0}", ex.Message), @"Ftp"); return(false); } } } return(result); }
/// <summary> /// Active FTP client /// </summary> public void Connecte() { if (!IsActiveFTPClient()) { _FTPClient = new FluentFTP.FtpClient(connection.ServerName, connection.User, new ADTool.Encryption.CryptLib().Decrypt(connection.Password)); _FTPClient.Connect(); } }
public void connect() { try { _client.Connect(); } catch (Exception ex) { throw new Exception("Cannot connect to the host. " + ex.Message, ex); } }
private FtpClient GetNewClient() { var _ftpClient = new FtpClient(_config.HostName); _ftpClient.Credentials = _config.Username == null ? new NetworkCredential() : new NetworkCredential(_config.Username, _config.Password); _ftpClient.SslProtocols = _config.SslProtocols; _ftpClient.DataConnectionEncryption = _ftpClient.EncryptionMode != FtpEncryptionMode.None; _ftpClient.Connect(); return(_ftpClient); }
public bool Connect(string host, int port, string username, string password) { try { FluentFTP.FtpTrace.EnableTracing = false; ftp = new FluentFTP.FtpClient(host, port, username, password); ftp.EnableThreadSafeDataConnections = false; ftp.TransferChunkSize = transferChunkSize; ftp.Connect(); return(ftp.IsConnected); } catch (Exception ex) { Trace.WriteLine(ex.Message); } return(false); }
/// <summary> /// 连接FTP /// </summary> /// <returns></returns> public bool Connect() { try { ftp = new FluentFTP.FtpClient(Host, Port, User, Password) { EncryptionMode = FtpEncryptionMode.None, ValidateAnyCertificate = true }; ftp.Connect(); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
private bool Save() { vm = this.DataContext as PersonViewModel; List <string> errors = vm.GetModelErrors(); var enterErrors = errors.Where(pp => /*!pp.StartsWith("Не прикреплен скан документа") && */ !pp.EndsWith(" не заполнено")); if (enterErrors.Any() && MessageBox.Show(string.Join(Environment.NewLine, enterErrors) + Environment.NewLine + "Чтобы поправить, нажмите Отмена", "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel) { return(false); } try { //await new ProgressRunner().RunAsync( // new Action<ProgressHandler>((progressChanged) => { //progressChanged(1, "Сохранение"); //MessageBox.Show(string.Join(Environment.NewLine, errors)); var db = new ProvodnikContext(); Person p; if (vm.Id.HasValue) { p = db.Persons.Single(pp => pp.Id == vm.Id.Value); MainWindow.Mapper.Value.Map(vm, p); var currents = vm.Documents.Where(pp => pp.Id.HasValue).Select(pp => pp.Id.Value).ToList(); var toDelete = (from pd in db.PersonDocs where pd.PersonId == p.Id && !currents.Contains(pd.Id) select pd); db.PersonDocs.RemoveRange(toDelete); db.SaveChanges(); } else { db.Persons.Add(p = new Person()); // { Fio = vm.Fio }); MainWindow.Mapper.Value.Map(vm, p); db.SaveChanges(); } //progressChanged(29, "Загрузка сканов"); var share = 70.0 / vm.Documents.Count; using (var client = new FluentFTP.FtpClient()) { App.ConfigureFtpClient(client); client.Connect(); foreach (var d in vm.Documents) { PersonDoc pd; if (d.Id.HasValue) { pd = db.PersonDocs.Single(pp => pp.Id == d.Id.Value); } else { db.PersonDocs.Add(pd = new PersonDoc() { PersonId = p.Id, IsActive = true, DocTypeId = d.DocTypeId, FileName = d.FileName }); db.SaveChanges(); } if (d.FileName == null) { ImageSource source = null; Application.Current.Dispatcher.Invoke((Action)(() => { source = d.Bitmap.Source; })); if (source != null) { var remotePath = $@"ProvodnikDocs/{p.Id.ToString()}/{DateTime.Now.Ticks}.jpg"; // "/1_Иванов"; while (client.Upload(ToByteArray(source as BitmapSource), remotePath, FtpRemoteExists.Overwrite, true) != FtpStatus.Success) { } //, FtpVerify.Retry); pd.FileName = remotePath; d.FileName = remotePath; //for GetScanErrors(true) /**/ /*using (WebClient wc = new WebClient() { Credentials = new NetworkCredential(App.CurrentConfig.FtpUser, App.CurrentConfig.FtpPassw) }) * { * var fileName = $@"{DateTime.Now.Ticks}.jpg"; * System.IO.File.Copy(d.LocalFileName, fileName); * * var remotePath = $@"ProvodnikDocs/{p.Id.ToString()}/";// "/1_Иванов"; * // wc.DownloadProgressChanged += wc_DownloadProgressChanged; * //wc.UploadFile("http://u0920601.plsk.regruhosting.ru/" +remotePath, "STOR", fileName); * //wc.UploadData("http://u0920601.plsk.regruhosting.ru/" + remotePath, "STOR", ToByteArray(source as BitmapSource)); * //HttpContent stringContent = new StringContent(paramString); * //HttpContent fileStreamContent = new StreamContent(paramFileStream); * var res= Upload("http://u0920601.plsk.regruhosting.ru/" + remotePath, ToByteArray(source as BitmapSource)); * // var ff= res.Result; * pd.FileName = remotePath; * d.FileName = remotePath; //for GetScanErrors(true) * }*/ } else { pd.FileName = null; } db.SaveChanges(); } pd.PrinesetK = d.PrinesetK; db.SaveChanges(); //progressChanged(share); } } vm.FillMessagesAndAlls(p); db.SaveChanges(); } //)); } catch (Exception ex) { MessageBox.Show(ex.Message); } //ProgressChanged(100); IsChanged = false; return(true); }
private async Task CreateFtpClientAsync(FtpConfig config, Func <string, Task <string> > securePasswordCallBack) { try { var passwd = await securePasswordCallBack.Invoke(config.Ftp.Credentials.AzureKeyVault.SecretName); var isRegistered = clientCollection.TryGetValue(config.Ftp.Host, out _ftpClient); if (!isRegistered) { var ftpClient = (config.Ftp.Protocol.Equals(FtpConstants.Ftps, StringComparison.InvariantCultureIgnoreCase) || config.Ftp.Port.Equals(990)) ? new FluentFTP.FtpClient(config.Ftp.Host) { //FTPS explicitly or Port = 990 => automatically create FTPS Credentials = new NetworkCredential(config.Ftp.Credentials.Username, passwd), Port = config.Ftp.Port, EnableThreadSafeDataConnections = true, DataConnectionType = config.Ftp.DataConnectionType == FtpConstants.FtpActiveMode ? FtpDataConnectionType.AutoActive : FtpDataConnectionType.AutoPassive, EncryptionMode = config.Ftp.Port.Equals(990) ? FtpEncryptionMode.Implicit : FtpEncryptionMode.Explicit } : new FluentFTP.FtpClient(config.Ftp.Host) { Credentials = new NetworkCredential(config.Ftp.Credentials.Username, await securePasswordCallBack.Invoke(config.Ftp.Credentials.AzureKeyVault.SecretName)), Port = config.Ftp.Port, EnableThreadSafeDataConnections = true }; ftpClient.ValidateCertificate += (control, e) => { e.Accept = (string.IsNullOrEmpty(config.Ftp.ValidateServerCertificate) || config.Ftp.ValidateServerCertificate.Equals("false", StringComparison.InvariantCultureIgnoreCase)) ? true : (e.Certificate.GetRawCertDataString() == config.Ftp.ValidateServerCertificate || e.PolicyErrors == SslPolicyErrors.None); }; _ftpClient = ftpClient; clientCollection.Add(config.Ftp.Host, ftpClient); } if (_ftpClient != null && !_ftpClient.IsConnected) { _ftpPolicyRegistry.GetPolicy(FtpPolicyName.FtpConnectPolicy).Execute(() => _ftpClient.Connect()); } } catch (Exception) { throw; } }
/// <summary> /// Opens a FXP PASV connection between the source FTP Server and the destination FTP Server /// </summary> /// <param name="remoteClient">FtpClient instance of the destination FTP Server</param> /// <returns>A data stream ready to be used</returns> private FtpFxpSession OpenPassiveFXPConnection(FtpClient remoteClient, bool trackProgress) { FtpReply reply; Match m; FtpClient sourceClient = null; FtpClient destinationClient = null; FtpClient progressClient = null; // create a new connection to the source FTP server if EnableThreadSafeDataConnections is set if (EnableThreadSafeDataConnections) { sourceClient = CloneConnection(); sourceClient._AutoDispose = true; sourceClient.CopyStateFlags(this); sourceClient.Connect(); sourceClient.SetWorkingDirectory(GetWorkingDirectory()); } else { sourceClient = this; } // create a new connection to the target FTP server if EnableThreadSafeDataConnections is set if (remoteClient.EnableThreadSafeDataConnections) { destinationClient = remoteClient.CloneConnection(); destinationClient._AutoDispose = true; destinationClient.CopyStateFlags(remoteClient); destinationClient.Connect(); destinationClient.SetWorkingDirectory(remoteClient.GetWorkingDirectory()); } else { destinationClient = remoteClient; } // create a new connection to the target FTP server to track progress // if progress tracking is enabled during this FXP transfer if (trackProgress) { progressClient = remoteClient.CloneConnection(); progressClient._AutoDispose = true; progressClient.CopyStateFlags(remoteClient); progressClient.Connect(); progressClient.SetWorkingDirectory(remoteClient.GetWorkingDirectory()); } sourceClient.SetDataType(sourceClient.FXPDataType); destinationClient.SetDataType(destinationClient.FXPDataType); // send PASV command to destination FTP server to get passive port to be used from source FTP server if (!(reply = destinationClient.Execute("PASV")).Success) { throw new FtpCommandException(reply); } m = Regex.Match(reply.Message, @"(?<quad1>\d+)," + @"(?<quad2>\d+)," + @"(?<quad3>\d+)," + @"(?<quad4>\d+)," + @"(?<port1>\d+)," + @"(?<port2>\d+)"); if (!m.Success || m.Groups.Count != 7) { throw new FtpException("Malformed PASV response: " + reply.Message); } // Instruct source server to open a connection to the destination Server if (!(reply = sourceClient.Execute($"PORT {m.Value}")).Success) { throw new FtpCommandException(reply); } // the FXP session stores the active connections used for this FXP transfer return(new FtpFxpSession { SourceServer = sourceClient, TargetServer = destinationClient, ProgressServer = progressClient, }); }