public override void GetFilesFromSource(CertificateTask task, IList <CertificateFile> files) { var catalogId = task.DocumentLine.ProductEntity.CatalogProduct.Id; var catalogs = GetSourceCatalog(catalogId, task.SerialNumber); if (catalogs.Count == 0) { task.DocumentLine.CertificateError = "Нет записи в таблице перекодировки"; return; } foreach (var certificateSourceCatalog in catalogs) { var filename = certificateSourceCatalog.OriginFilePath; var mask = String.Format("{0}*{1}", Path.GetFileNameWithoutExtension(filename), Path.GetExtension(filename)); var uri = new Uri(task.CertificateSource.LookupUrl); var dir = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath) ?? "", Path.GetDirectoryName(certificateSourceCatalog.OriginFilePath) ?? ""); using (var ftpClient = new FTP_Client()) { ftpClient.PassiveMode = true; ftpClient.Connect(uri.Host, uri.Port); var credentials = Util.GetCredentials(uri); if (credentials != null) { ftpClient.Authenticate(credentials.UserName, credentials.Password); } else { ftpClient.Authenticate("anonymous", ""); } if (!String.IsNullOrEmpty(dir)) { ftpClient.SetCurrentDir(dir); } var ftpFiles = ftpClient.GetList(); var filesToDownload = ftpFiles.Tables["DirInfo"] .AsEnumerable() .Where(r => !Convert.ToBoolean(r["IsDirectory"])) .Select(r => r["Name"].ToString()) .Where(n => FileHelper.CheckMask(n, mask)) .ToList(); foreach (var file in filesToDownload) { var tempFileName = Path.GetTempFileName(); ftpClient.ReceiveFile(file, tempFileName); files.Add(new CertificateFile( tempFileName, certificateSourceCatalog.OriginFilePath, file, task.CertificateSource)); } } } if (files.Count == 0) { task.DocumentLine.CertificateError = "Файл сертификата не найден на ftp поставщика"; } }
/// <summary> /// Пытается загрузить файл. После 3х неудачных попыток последнее исключение отдается наверх /// </summary> /// <param name="ftpClient">Объект FTP клиента</param> /// <param name="fileInDirectory">Имя файла в текущей FTP директории</param> /// <param name="downloadedFileName">Путь к файлу, куда он должен быть загружен</param> private void ReceiveFile(FTP_Client ftpClient, string fileInDirectory, string downloadedFileName) { var countAttempts = 3; for (var i = 0; i < countAttempts; i++) { try { if (File.Exists(downloadedFileName)) { _log.DebugFormat("Загрузка файла. Файл {0} уже существует. Удаляем", downloadedFileName); File.Delete(downloadedFileName); } using (var fileStream = new FileStream(downloadedFileName, FileMode.CreateNew)) { ftpClient.ReceiveFile(fileInDirectory, fileStream); return; } } catch (Exception) { if (i >= countAttempts) { throw; } } } }
public static DownloadedFile GetFileFromSource(PriceSource source, string downHandlerPath) { var ftpHost = source.PricePath; if (ftpHost.StartsWith(@"ftp://", StringComparison.OrdinalIgnoreCase)) { ftpHost = ftpHost.Substring(6); } if (ftpHost.EndsWith(@"/")) { ftpHost = ftpHost.Substring(0, ftpHost.Length - 1); } var pricePath = source.FtpDir; if (!pricePath.StartsWith(@"/", StringComparison.OrdinalIgnoreCase)) { pricePath = @"/" + pricePath; } var ftpFileName = String.Empty; var downFileName = String.Empty; var shortFileName = String.Empty; var priceDateTime = source.PriceDateTime; using (var ftpClient = new FTP_Client()) { ftpClient.PassiveMode = true; ftpClient.Connect(ftpHost, 21); ftpClient.Authenticate(source.FtpLogin, source.FtpPassword); ftpClient.SetCurrentDir(pricePath); var dsEntries = ftpClient.GetList(); foreach (DataRow entry in dsEntries.Tables["DirInfo"].Rows) { if (Convert.ToBoolean(entry["IsDirectory"])) { continue; } shortFileName = entry["Name"].ToString(); var priceMaskIsMatched = PriceProcessor.FileHelper.CheckMask(shortFileName, source.PriceMask); if (priceMaskIsMatched) { var fileLastWriteTime = Convert.ToDateTime(entry["Date"]); #if DEBUG priceDateTime = fileLastWriteTime; ftpFileName = shortFileName; #endif if (((fileLastWriteTime.CompareTo(priceDateTime) > 0) && (DateTime.Now.Subtract(fileLastWriteTime).TotalMinutes > Settings.Default.FileDownloadInterval)) || ((fileLastWriteTime.CompareTo(DateTime.Now) > 0) && (fileLastWriteTime.Subtract(priceDateTime).TotalMinutes > 0))) { priceDateTime = fileLastWriteTime; ftpFileName = shortFileName; } } } if (String.IsNullOrEmpty(ftpFileName)) { return(null); } downFileName = Path.Combine(downHandlerPath, ftpFileName); using (var file = new FileStream(downFileName, FileMode.Create)) ftpClient.ReceiveFile(ftpFileName, file); } return(new DownloadedFile(downFileName, priceDateTime)); }