static void UploadFile(string _FileName, string _UploadPath, string _FTPUser, string _FTPPass) { System.IO.FileInfo _FileInfo = new System.IO.FileInfo(_FileName); System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(_UploadPath)); _FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass); _FtpWebRequest.KeepAlive = false; _FtpWebRequest.Timeout = 20000; _FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; _FtpWebRequest.UseBinary = true; _FtpWebRequest.ContentLength = _FileInfo.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; System.IO.FileStream _FileStream = _FileInfo.OpenRead(); try { System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream(); int contentLen = _FileStream.Read(buff, 0, buffLength); while (contentLen != 0) { _Stream.Write(buff, 0, contentLen); contentLen = _FileStream.Read(buff, 0, buffLength); } _Stream.Close(); _Stream.Dispose(); _FileStream.Close(); _FileStream.Dispose(); } catch (Exception ex) { loguj("Błąd FTP: " + ex.Message.ToString()); } }
public static string SaveUploadedFileToFtp(ColumnField field, string strFileName, string contentType, System.IO.Stream stream) { if (!field.FtpUpload.Override && CheckIfFileExistInFtp(field, strFileName)) { throw new DuradosException(field.View.Database.Localizer.Translate("File with same name already exist")); } System.Net.FtpWebRequest request = CreateFtpRequest(field, strFileName); request.Method = System.Net.WebRequestMethods.Ftp.UploadFile; byte[] buffer = new byte[stream.Length]; //StreamReader sourceStream = new StreamReader(stream); //Only for text files !!! //byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());//Only for text files !!! int count = stream.Read(buffer, 0, buffer.Length); request.ContentLength = buffer.Length; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(buffer, 0, buffer.Length); } System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)request.GetResponse(); response.Close(); return(string.Empty);//response.StatusCode / response.StatusDescription }
public static System.Net.FtpWebResponse FtpUpload(string localFilePath, string ftpUrl, string ftpPath, string ftpUsername, string ftpPassword, bool usePassive = false) { // aggiunge il nome del file ftpPath = System.IO.Path.Combine(ftpPath, System.IO.Path.GetFileName(localFilePath)); System.Net.FtpWebRequest request = FtpRequest( ftpUrl: ftpUrl, ftpPath: ftpPath, ftpUsername: ftpUsername, ftpPassword: ftpPassword, ftpMethod: System.Net.WebRequestMethods.Ftp.UploadFile, usePassive: usePassive ); byte[] fileContents; using (System.IO.StreamReader sourceStream = new System.IO.StreamReader(localFilePath)) { fileContents = System.Text.Encoding.UTF8.GetBytes(sourceStream.ReadToEnd()); } request.ContentLength = fileContents.Length; using (System.IO.Stream requestStream = request.GetRequestStream()) { requestStream.Write(fileContents, 0, fileContents.Length); } return((System.Net.FtpWebResponse)request.GetResponse()); }
public static void FtpUpload(string ftpPath, string user, string pwd, string inputFile) { //string ftpPath = "ftp://ftp.test.com/home/myindex.txt"; //string user = "******"; //string pwd = "ftppwd"; //string inputFile = "index.txt"; // WebRequest.Create로 Http,Ftp,File Request 객체를 모두 생성할 수 있다. System.Net.FtpWebRequest req = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpPath); // FTP 업로드한다는 것을 표시 req.Method = System.Net.WebRequestMethods.Ftp.UploadFile; // 쓰기 권한이 있는 FTP 사용자 로그인 지정 req.Credentials = new System.Net.NetworkCredential(user, pwd); // 입력파일을 바이트 배열로 읽음 byte[] data; using (StreamReader reader = new StreamReader(inputFile)) { data = Encoding.UTF8.GetBytes(reader.ReadToEnd()); } // RequestStream에 데이타를 쓴다 req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); } // FTP Upload 실행 using (System.Net.FtpWebResponse resp = (System.Net.FtpWebResponse)req.GetResponse()) { // FTP 결과 상태 출력 Console.WriteLine("Upload: {0}", resp.StatusDescription); } }
private bool Upload(FileInfo fi, string targetFilename) { //copy the file specified to target file: target file can be full path or just filename (uses current dir) string host = this.gbaseFtpField.Text.Trim(); if (host.EndsWith("/") == false) { host = host + "/"; } string URI = host + targetFilename; //perform copy System.Net.FtpWebRequest ftp = GetRequest(URI); //Set request to upload a file in binary ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftp.UseBinary = true; //Notify FTP of the expected size ftp.ContentLength = fi.Length; //create byte array to store: ensure at least 1 byte! const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1]; int dataRead; //open file for reading using (FileStream fs = fi.OpenRead()) { try { //open request to send using (Stream rs = ftp.GetRequestStream()) { do { dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); }while (!(dataRead < BufferSize)); rs.Close(); } } catch (Exception ex) { EventLog.LogEvent(ex); } finally { //ensure file closed fs.Close(); } } ftp = null; return(true); }
/// <summary> /// 上传文件 /// </summary> /// <param name="url"></param> /// <param name="upFile"></param> /// <param name="username"></param> /// <param name="password"></param> public Boolean uploadFile(string url, string upFile, string username, string password) { Boolean ret = true; try { //アップロード先のURI Uri u = new Uri(url); //FtpWebRequestの作成 System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest) System.Net.WebRequest.Create(u); //ログインユーザー名とパスワードを設定 ftpReq.Credentials = new System.Net.NetworkCredential(username, password); //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定 ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //要求の完了後に接続を閉じる ftpReq.KeepAlive = false; //ASCIIモードで転送する ftpReq.UseBinary = true; //PASVモードを無効にする ftpReq.UsePassive = false; //ファイルをアップロードするためのStreamを取得 System.IO.Stream reqStrm = ftpReq.GetRequestStream(); //アップロードするファイルを開く System.IO.FileStream fs = new System.IO.FileStream( upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read); //アップロードStreamに書き込む byte[] buffer = new byte[1024]; while (true) { int readSize = fs.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } reqStrm.Write(buffer, 0, readSize); } fs.Close(); reqStrm.Close(); //FtpWebResponseを取得 System.Net.FtpWebResponse ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse(); //閉じる ftpRes.Close(); } catch (Exception ex) { NCLogger.GetInstance().WriteExceptionLog(ex); ret = false; } return(ret); }
/// <summary> /// エラーファイルをサーバにアップロードする /// </summary> /// <param name="strErrLogPath"></param> private void ErrMsgUpload(string strErrLogPath) { try { string upFile = strErrLogPath; Uri u = new Uri("ftp://aaa" + Path.GetFileName(strErrLogPath)); System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest) System.Net.WebRequest.Create(u); ftpReq.Credentials = new System.Net.NetworkCredential("aaaa", "aaaa"); ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftpReq.KeepAlive = false; ftpReq.UseBinary = false; ftpReq.UsePassive = false; System.IO.Stream reqStrm = ftpReq.GetRequestStream(); using (System.IO.FileStream fs = new System.IO.FileStream( upFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { byte[] buffer = new byte[1024]; while (true) { int readSize = fs.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } reqStrm.Write(buffer, 0, readSize); } fs.Close(); } reqStrm.Close(); System.Net.FtpWebResponse ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse(); Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription); ftpRes.Close(); } catch (System.Exception) { } }
private void ExecLocalDistantImage(Model.Local.Catalog Catalog, Model.Prestashop.PsCategory PsCategory) { // We need to send pictures Model.Local.CatalogImageRepository CatalogImageRepository = new Model.Local.CatalogImageRepository(); Model.Local.CatalogImage CatalogImage = CatalogImageRepository.ReadCatalog(Catalog.Cat_Id, true); if (CatalogImage != null) { Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository(); List <Model.Prestashop.PsImageType> ListPsImageType = PsImageTypeRepository.ListCategorie(1); if (Core.Global.GetConfig().ConfigFTPActive) { String FTP = Core.Global.GetConfig().ConfigFTPIP; String User = Core.Global.GetConfig().ConfigFTPUser; String Password = Core.Global.GetConfig().ConfigFTPPassword; string extension = System.IO.Path.GetExtension(CatalogImage.ImaCat_Image); String PathImgTmp = System.IO.Path.Combine(Global.GetConfig().Folders.TempCatalog, String.Format("{0}" + extension, CatalogImage.ImaCat_Id)); if (System.IO.File.Exists(PathImgTmp)) { string ftpfullpath = FTP + "/img/c/" + PsCategory.IDCategory + ".jpg"; System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); //userid and password for the ftp server to given ftp.UseBinary = true; ftp.UsePassive = true; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; System.IO.FileStream fs = System.IO.File.OpenRead(PathImgTmp); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); System.IO.Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftp.Abort(); foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType) { String PathImg = System.IO.Path.Combine(Global.GetConfig().Folders.RootCatalog, String.Format("{0}-{1}" + extension, CatalogImage.ImaCat_Id, PsImageType.Name)); if (System.IO.File.Exists(PathImg)) { ftpfullpath = FTP + "/img/c/" + PsCategory.IDCategory + "-" + PsImageType.Name + ".jpg"; ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); //userid and password for the ftp server to given ftp.UseBinary = true; ftp.UsePassive = true; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; fs = System.IO.File.OpenRead(PathImg); buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftp.Abort(); } } Core.Temp.SyncCatalogue_ClearSmartyCache = true; Core.Temp.SyncCatalogue_RegenerateTree = true; } } } }
//<YH> 23/08/2012 private void ExecLocalToDistant(Model.Local.Article Article) { try { Model.Prestashop.PsAttachmentRepository PsAttachmentRepository = new Model.Prestashop.PsAttachmentRepository(); Model.Prestashop.PsAttachment PsAttachment; Model.Prestashop.PsAttachmentLangRepository PsAttachmentLangRepository = new Model.Prestashop.PsAttachmentLangRepository(); Model.Prestashop.PsAttachmentLang PsAttachmentLang; Model.Prestashop.PsProductAttachmentRepository PsProductAttachmentRepository = new Model.Prestashop.PsProductAttachmentRepository(); Model.Prestashop.PsProductAttachment PsProductAttachment; Boolean isAttachmentLang = false; String FTP = Core.Global.GetConfig().ConfigFTPIP; String User = Core.Global.GetConfig().ConfigFTPUser; String Password = Core.Global.GetConfig().ConfigFTPPassword; Model.Local.AttachmentRepository AttachmentRepository = new Model.Local.AttachmentRepository(); List <Model.Local.Attachment> ListAttachment = AttachmentRepository.ListArticle(Article.Art_Id); foreach (Model.Local.Attachment Attachment in ListAttachment) { try { if (Attachment.Pre_Id == null) { String PathAttachment = Path.Combine(Global.GetConfig().Folders.RootAttachment, Attachment.Att_File); if (System.IO.File.Exists(PathAttachment)) { #region infos document joint PsAttachment = new Model.Prestashop.PsAttachment(); PsAttachment.File = Attachment.Att_File; PsAttachment.FileName = Attachment.Att_FileName; PsAttachment.Mime = Attachment.Att_Mime; PsAttachmentRepository.Add(PsAttachment); isAttachmentLang = false; PsAttachmentLang = new Model.Prestashop.PsAttachmentLang(); if (PsAttachmentLangRepository.ExistAttachmentLang(PsAttachment.IDAttachment, Core.Global.Lang)) { PsAttachmentLang = PsAttachmentLangRepository.ReadAttachmentLang(PsAttachment.IDAttachment, Core.Global.Lang); isAttachmentLang = true; } PsAttachmentLang.Name = Attachment.Att_Name; PsAttachmentLang.Description = Attachment.Att_Description; if (isAttachmentLang == true) { PsAttachmentLangRepository.Save(); } else { PsAttachmentLang.IDAttachment = PsAttachment.IDAttachment; PsAttachmentLang.IDLang = Core.Global.Lang; PsAttachmentLangRepository.Add(PsAttachmentLang); } #endregion // <JG> 24/05/2013 ajout insertion autres langues actives si non renseignées #region Multi-langues try { Model.Prestashop.PsLangRepository PsLangRepository = new Model.Prestashop.PsLangRepository(); foreach (Model.Prestashop.PsLang PsLang in PsLangRepository.ListActive(1, Global.CurrentShop.IDShop)) { if (!PsAttachmentLangRepository.ExistAttachmentLang(PsAttachment.IDAttachment, PsLang.IDLang)) { PsAttachmentLang = new Model.Prestashop.PsAttachmentLang() { IDAttachment = PsAttachment.IDAttachment, IDLang = PsLang.IDLang, Name = Attachment.Att_Name, Description = Attachment.Att_Description }; PsAttachmentLangRepository.Add(PsAttachmentLang); } } } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); } #endregion // affectation au produit PsProductAttachment = new Model.Prestashop.PsProductAttachment(); if (PsProductAttachmentRepository.ExistProductAttachment(Convert.ToUInt32(Article.Pre_Id), PsAttachment.IDAttachment) == false) { PsProductAttachment.IDProduct = Convert.ToUInt32(Article.Pre_Id); PsProductAttachment.IDAttachment = PsAttachment.IDAttachment; PsProductAttachmentRepository.Add(PsProductAttachment); } try { #region upload string ftpfullpath = FTP + "/download/" + Attachment.Att_File; System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); //userid and password for the ftp server to given ftp.UseBinary = true; ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; System.IO.FileStream fs = System.IO.File.OpenRead(PathAttachment); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); System.IO.Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftp.Abort(); #endregion #region update Product field cache_as_attachements Model.Prestashop.PsProductRepository PsProductRepository = new Model.Prestashop.PsProductRepository(); Model.Prestashop.PsProduct PsProduct = PsProductRepository.ReadId(PsProductAttachment.IDProduct); if (PsProduct.CacheHasAttachments == 0) { PsProduct.CacheHasAttachments = (sbyte)1; PsProductRepository.Save(); } #endregion Attachment.Pre_Id = Convert.ToInt32(PsAttachment.IDAttachment); AttachmentRepository.Save(); } catch (Exception ex) { Core.Error.SendMailError("[UPLOAD FTP DOCUMENT]<br />" + ex.ToString()); PsProductAttachmentRepository.Delete(PsProductAttachmentRepository.ListAttachment(PsAttachment.IDAttachment)); PsAttachmentLangRepository.Delete(PsAttachmentLangRepository.ListAttachment(PsAttachment.IDAttachment)); PsAttachmentRepository.Delete(PsAttachment); } } } } catch (Exception ex) { Core.Error.SendMailError("[SYNCHRO DOCUMENT ARTICLE]<br />" + ex.ToString()); } } } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); } }
public Boolean Exec(String PathImg, Int32 ArticleSend, int position, int Declination) { Boolean result = false; Int32 IdArticleImage = 0; try { String extension = Path.GetExtension(PathImg); String FileName = Path.GetFileName(PathImg); Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository(); if (!ArticleImageRepository.ExistArticleFile(ArticleSend, FileName)) { Model.Local.ArticleRepository ArticleRepository = new Model.Local.ArticleRepository(); Model.Local.Article Article = ArticleRepository.ReadArticle(ArticleSend); Model.Local.ArticleImage ArticleImage = new Model.Local.ArticleImage() { Art_Id = Article.Art_Id, ImaArt_Name = Article.Art_Name, ImaArt_Image = "", ImaArt_DateAdd = DateTime.Now, ImaArt_SourceFile = FileName }; ArticleImage.ImaArt_Position = this.ReadNextPosition(Article, position); ArticleImage.ImaArt_Default = !(new Model.Local.ArticleImageRepository().ExistArticleDefault(Article.Art_Id, true)); ArticleImageRepository.Add(ArticleImage); ArticleImage.ImaArt_Image = String.Format("{0}" + extension, ArticleImage.ImaArt_Id); ArticleImageRepository.Save(); IdArticleImage = ArticleImage.ImaArt_Id; string uri = PathImg.Replace("File:///", "").Replace("file:///", "").Replace("File://", "\\\\").Replace("file://", "\\\\").Replace("/", "\\"); System.IO.File.Copy(uri, ArticleImage.TempFileName); Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository(); List <Model.Prestashop.PsImageType> ListPsImageType = PsImageTypeRepository.ListProduct(1); System.Drawing.Image img = System.Drawing.Image.FromFile(ArticleImage.TempFileName); foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType) { Core.Img.resizeImage(img, Convert.ToInt32(PsImageType.Width), Convert.ToInt32(PsImageType.Height), ArticleImage.FileName(PsImageType.Name)); } Core.Img.resizeImage(img, Core.Global.GetConfig().ConfigImageMiniatureWidth, Core.Global.GetConfig().ConfigImageMiniatureHeight, ArticleImage.SmallFileName); img.Dispose(); // <JG> 28/10/2015 ajout attribution gamme/images if (Declination != 0) { if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMonoGamme || ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMultiGammes) { Model.Local.AttributeArticleRepository AttributeArticleRepository = new Model.Local.AttributeArticleRepository(); if (AttributeArticleRepository.Exist(Declination)) { Model.Local.AttributeArticleImageRepository AttributeArticleImageRepository = new Model.Local.AttributeArticleImageRepository(); if (!AttributeArticleImageRepository.ExistAttributeArticleImage(Declination, ArticleImage.ImaArt_Id)) { AttributeArticleImageRepository.Add(new Model.Local.AttributeArticleImage() { AttArt_Id = Declination, ImaArt_Id = ArticleImage.ImaArt_Id, }); } } } else if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleComposition) { Model.Local.CompositionArticleRepository CompositionArticleRepository = new Model.Local.CompositionArticleRepository(); if (CompositionArticleRepository.Exist(Declination)) { Model.Local.CompositionArticleImageRepository CompositionArticleImageRepository = new Model.Local.CompositionArticleImageRepository(); if (!CompositionArticleImageRepository.ExistCompositionArticleImage(Declination, ArticleImage.ImaArt_Id)) { CompositionArticleImageRepository.Add(new Model.Local.CompositionArticleImage() { ComArt_Id = Declination, ImaArt_Id = ArticleImage.ImaArt_Id, }); } } } } result = true; } else if (Core.Global.GetConfig().ImportImageReplaceFiles) { FileInfo importfile = new FileInfo(PathImg); Model.Local.ArticleImage ArticleImage = ArticleImageRepository.ReadArticleFile(ArticleSend, FileName); FileInfo existfile = new FileInfo(ArticleImage.TempFileName); if ((ArticleImage.ImaArt_DateAdd == null || importfile.LastWriteTime > ArticleImage.ImaArt_DateAdd) || importfile.Length != existfile.Length) { try { // import nouveau fichier string uri = PathImg.Replace("File:///", "").Replace("file:///", "").Replace("File://", "\\\\").Replace("file://", "\\\\").Replace("/", "\\"); System.IO.File.Copy(uri, ArticleImage.TempFileName, true); Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository(); List <Model.Prestashop.PsImageType> ListPsImageType = PsImageTypeRepository.ListProduct(1); System.Drawing.Image img = System.Drawing.Image.FromFile(ArticleImage.TempFileName); foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType) { Core.Img.resizeImage(img, Convert.ToInt32(PsImageType.Width), Convert.ToInt32(PsImageType.Height), ArticleImage.FileName(PsImageType.Name)); } Core.Img.resizeImage(img, Core.Global.GetConfig().ConfigImageMiniatureWidth, Core.Global.GetConfig().ConfigImageMiniatureHeight, ArticleImage.SmallFileName); Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository(); if (ArticleImage.Pre_Id != null && PsImageRepository.ExistImage((uint)ArticleImage.Pre_Id)) { String FTP = Core.Global.GetConfig().ConfigFTPIP; String User = Core.Global.GetConfig().ConfigFTPUser; String Password = Core.Global.GetConfig().ConfigFTPPassword; Model.Prestashop.PsImage PsImage = PsImageRepository.ReadImage((uint)ArticleImage.Pre_Id); string ftpPath = "/img/p/"; switch (Core.Global.GetConfig().ConfigImageStorageMode) { case Core.Parametres.ImageStorageMode.old_system: #region old_system // no action on path break; #endregion case Core.Parametres.ImageStorageMode.new_system: default: #region new_system //System.Net.FtpWebRequest ftp_folder = null; foreach (char directory in PsImage.IDImage.ToString()) { ftpPath += directory + "/"; #region MyRegion try { System.Net.FtpWebRequest request = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(FTP + ftpPath); request.Credentials = new System.Net.NetworkCredential(User, Password); request.UsePassive = true; request.UseBinary = true; request.KeepAlive = false; request.Method = System.Net.WebRequestMethods.Ftp.MakeDirectory; System.Net.FtpWebResponse makeDirectoryResponse = (System.Net.FtpWebResponse)request.GetResponse(); } catch //Exception ex { //System.Windows.MessageBox.Show(ex.ToString()); } #endregion } break; #endregion } #region Upload des images extension = ArticleImage.GetExtension; if (System.IO.File.Exists(ArticleImage.TempFileName)) { string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system) ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + ".jpg" : FTP + ftpPath + PsImage.IDImage + ".jpg"; System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); //userid and password for the ftp server to given ftp.UseBinary = true; ftp.UsePassive = true; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; System.IO.FileStream fs = System.IO.File.OpenRead(ArticleImage.TempFileName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); System.IO.Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftp.Abort(); } foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType) { String localfile = ArticleImage.FileName(PsImageType.Name); if (System.IO.File.Exists(localfile)) { string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system) ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + "-" + PsImageType.Name + ".jpg" : FTP + ftpPath + PsImage.IDImage + "-" + PsImageType.Name + ".jpg"; System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath); ftp.Credentials = new System.Net.NetworkCredential(User, Password); //userid and password for the ftp server to given ftp.UseBinary = true; ftp.UsePassive = true; ftp.EnableSsl = Core.Global.GetConfig().ConfigFTPSSL; ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; System.IO.FileStream fs = System.IO.File.OpenRead(localfile); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); System.IO.Stream ftpstream = ftp.GetRequestStream(); ftpstream.Write(buffer, 0, buffer.Length); ftpstream.Close(); ftp.Abort(); } } #endregion } ArticleImage.ImaArt_DateAdd = DateTime.Now; ArticleImageRepository.Save(); // <JG> 28/10/2015 ajout attribution gamme/images if (Declination != 0) { if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMonoGamme || ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleMultiGammes) { Model.Local.AttributeArticleRepository AttributeArticleRepository = new Model.Local.AttributeArticleRepository(); if (AttributeArticleRepository.Exist(Declination)) { Model.Local.AttributeArticleImageRepository AttributeArticleImageRepository = new Model.Local.AttributeArticleImageRepository(); if (!AttributeArticleImageRepository.ExistAttributeArticleImage(Declination, ArticleImage.ImaArt_Id)) { AttributeArticleImageRepository.Add(new Model.Local.AttributeArticleImage() { AttArt_Id = Declination, ImaArt_Id = ArticleImage.ImaArt_Id, }); } // réaffectation côté PrestaShop Model.Local.AttributeArticle AttributeArticle = AttributeArticleRepository.Read(Declination); if (AttributeArticle.Pre_Id != null && AttributeArticle.Pre_Id != 0) { Model.Prestashop.PsProductAttributeImageRepository PsProductAttributeImageRepository = new Model.Prestashop.PsProductAttributeImageRepository(); if (PsProductAttributeImageRepository.ExistProductAttributeImage((UInt32)AttributeArticle.Pre_Id, (UInt32)ArticleImage.Pre_Id) == false) { PsProductAttributeImageRepository.Add(new Model.Prestashop.PsProductAttributeImage() { IDImage = (UInt32)ArticleImage.Pre_Id, IDProductAttribute = (UInt32)AttributeArticle.Pre_Id, }); } } } } else if (ArticleImage.Article.TypeArticle == Model.Local.Article.enum_TypeArticle.ArticleComposition) { Model.Local.CompositionArticleRepository CompositionArticleRepository = new Model.Local.CompositionArticleRepository(); if (CompositionArticleRepository.Exist(Declination)) { Model.Local.CompositionArticleImageRepository CompositionArticleImageRepository = new Model.Local.CompositionArticleImageRepository(); if (!CompositionArticleImageRepository.ExistCompositionArticleImage(Declination, ArticleImage.ImaArt_Id)) { CompositionArticleImageRepository.Add(new Model.Local.CompositionArticleImage() { ComArt_Id = Declination, ImaArt_Id = ArticleImage.ImaArt_Id, }); } // réaffectation côté PrestaShop Model.Local.CompositionArticle CompositionArticle = CompositionArticleRepository.Read(Declination); if (CompositionArticle.Pre_Id != null && CompositionArticle.Pre_Id != 0) { Model.Prestashop.PsProductAttributeImageRepository PsProductAttributeImageRepository = new Model.Prestashop.PsProductAttributeImageRepository(); if (PsProductAttributeImageRepository.ExistProductAttributeImage((UInt32)CompositionArticle.Pre_Id, (UInt32)ArticleImage.Pre_Id) == false) { PsProductAttributeImageRepository.Add(new Model.Prestashop.PsProductAttributeImage() { IDImage = (UInt32)ArticleImage.Pre_Id, IDProductAttribute = (UInt32)CompositionArticle.Pre_Id, }); } } } } } result = true; logs.Add("II30- Remplacement de l'image " + ArticleImage.ImaArt_SourceFile + " en position " + ArticleImage.ImaArt_Position + " pour l'article " + ArticleImage.Article.Art_Ref); } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); logs.Add("II39- Erreur lors du remplacement de l'image " + ArticleImage.ImaArt_SourceFile + " en position " + ArticleImage.ImaArt_Position + " pour l'article " + ArticleImage.Article.Art_Ref); logs.Add(ex.ToString()); } } } } catch (Exception ex) { Core.Error.SendMailError(ex.ToString()); if (ex.ToString().Contains("System.UnauthorizedAccessException") && IdArticleImage != 0) { Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository(); ArticleImageRepository.Delete(ArticleImageRepository.ReadArticleImage(IdArticleImage)); } } return(result); }
private static void TransferFiletoFTP(string serviceName, object jobDetails, string jobFile) { DateTime dtJobReleaseStart = DateTime.Now; DataRow drPrintJob = jobDetails as DataRow; string jobDBID = drPrintJob["REC_SYSID"].ToString(); string jobFileName = drPrintJob["JOB_FILE"].ToString(); if (!string.IsNullOrEmpty(jobFile)) { jobFileName = jobFile; } string destinationFTPPath = drPrintJob["JOB_FTP_PATH"].ToString(); string ftpUserName = drPrintJob["JOB_FTP_ID"].ToString(); string ftpUserPassword = drPrintJob["JOB_FTP_PASSWORD"].ToString(); string isDeleteFile = drPrintJob["DELETE_AFTER_PRINT"].ToString(); try { string message = string.Format("File Transfer to MFP started @ {0}", DateTime.Now.ToString()); LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Detailed, message, "", "", ""); System.IO.FileInfo fileInfo = new System.IO.FileInfo(jobFileName); // Create FtpWebRequest object from the Uri provided System.Net.FtpWebRequest ftpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(destinationFTPPath)); // Provide the WebPermission Credintials ftpWebRequest.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpUserPassword); ftpWebRequest.Proxy = null; //ftpWebRequest.ConnectionGroupName = jobFileName; // By default KeepAlive is true, where the control connection is not closed // after a command is executed. ftpWebRequest.KeepAlive = false; // set timeout for 20 seconds ftpWebRequest.Timeout = 30000; // Specify the command to be executed. ftpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. ftpWebRequest.UseBinary = true; // Notify the server about the size of the uploaded file ftpWebRequest.ContentLength = fileInfo.Length; // The buffer size is set to 4MB int buffLength = 4 * 1024 * 1024; byte[] buff = new byte[buffLength]; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded System.IO.FileStream fileStream = fileInfo.OpenRead(); // Stream to which the file to be upload is written System.IO.Stream stream = ftpWebRequest.GetRequestStream(); // Read from the file stream 4MB at a time int contentLen = fileStream.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream stream.Write(buff, 0, contentLen); contentLen = fileStream.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream fileStream.Close(); fileStream.Dispose(); stream.Close(); stream.Dispose(); DateTime dtJobReleaseEnd = DateTime.Now; UpdateJobReleaseTimings(serviceName, drPrintJob["JOB_FILE"].ToString().Replace("_PDFinal", "_PD"), dtJobReleaseStart, dtJobReleaseEnd, jobDBID); if (isDeleteFile.ToLower() == "true") { DeletePrintJobsFile(serviceName, jobFileName); } message = string.Format("File transferred to MFP, file : {0}", jobFileName); LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Detailed, message, "", "", ""); } catch (Exception ex) { //MessageBox.Show(ex.Message, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error); LogManager.RecordMessage(serviceName, "TransferFiletoFTP", LogManager.MessageType.Exception, ex.Message, "Restart the Print Data Provider Service", ex.Message, ex.StackTrace); } }
/** * @brief OneFile ftp upload * @param[in] string name login name * @param[in] string pass password * @param[in] string uri UploadするFileの URI 例"ftp://localhost/test_e.exe" * @param[in] string local_path :UploadするFileの場所 例"C:\\test_e.exe" * @return bool true:ok false:error */ public bool FtpOneFileUp(string name, string pass, string uri, string local_path) { Uri uri_obj = new Uri(uri); string upFilePath = local_path; err_msg_str = "no info."; // FtpWebRequestの作成 System.Net.FtpWebRequest ftp_req = (System.Net.FtpWebRequest) System.Net.WebRequest.Create(uri_obj); // ログインユーザー名とパスワードを設定 ftp_req.Credentials = new System.Net.NetworkCredential(name, pass); // MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定 ftp_req.Method = System.Net.WebRequestMethods.Ftp.UploadFile; ftp_req.KeepAlive = false; // 要求の完了後に接続を閉じる ftp_req.UseBinary = false; // Binaryモードで転送する ftp_req.UsePassive = true; // PASSIVEモードを有効にする bool ok_f = true; System.IO.Stream res_strm = null; try { // ファイルをアップロードするためのStreamを取得 res_strm = ftp_req.GetRequestStream(); } catch (System.Net.WebException e_msg) { ok_f = false; err_msg_str = e_msg.Message; if (res_strm != null) { res_strm.Close(); } } if (ok_f == true) { // アップロードするためのFileStreamを作成 System.IO.FileStream fs = null; fs = new System.IO.FileStream(upFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); try { // アップロード用Streamにデータを書き込む int size = 1024; byte[] buffer = new byte[size]; while (true) { int readSize = fs.Read(buffer, 0, buffer.Length); if (readSize == 0) { break; } res_strm.Write(buffer, 0, readSize); } } catch (System.IO.IOException ie) { Console.WriteLine("", ie.Message); } finally { if (fs != null) { fs.Close(); } if (res_strm != null) { res_strm.Close(); } } return(true); } else { return(false); } }