The FtpWebResponse class contains the result of the FTP request interface.

상속: WebResponse, IDisposable
예제 #1
1
        /// <summary>
        /// 连接FTP的方法
        /// </summary>
        /// <param name="ftpuri">ftp服务器地址,端口</param>
        /// <param name="ftpUserID">用户名</param>
        /// <param name="ftpPassword">密码</param>
        public DownloadFtp(string ftpuri, string ftpUserID, string ftpPassword)
        {
            // 根据uri创建FtpWebRequest对象
              ft = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpuri));
              // ftp用户名和密码
              ft.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
              ft.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
             fr = (FtpWebResponse)ft.GetResponse();
              stream = fr.GetResponseStream();
              ////二进制文件读入
              //if (!fr.ContentType.ToLower().StartsWith("text/"))
              //{
              //    SaveBinaryFile(fr);
              //}
              ////文本文件
              //else
              //{
              string buffer = "", line;
              StreamReader reader = new StreamReader(stream);
              while ((line = reader.ReadLine()) != null)
              {
                  buffer += line + "\r\n";
              }

              //装入整个文件之后,接着就要把它保存为文本文件。
              SaveTextFile(buffer);
              //}
        }
예제 #2
0
 /* Create a New Directory on the FTP Server */
 public bool createDirectory(string newDirectory)
 {
     bool result = true;
      try
      {
     /* Create an FTP Request */
     ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
     /* Log in to the FTP Server with the User Name and Password Provided */
     ftpRequest.Credentials = new NetworkCredential(user, pass);
     /* When in doubt, use these options */
     ftpRequest.UseBinary = true;
     ftpRequest.UsePassive = true;
     ftpRequest.KeepAlive = true;
     /* Specify the Type of FTP Request */
     ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
     /* Establish Return Communication with the FTP Server */
     ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
     /* Resource Cleanup */
     ftpResponse.Close();
     ftpRequest = null;
      }
      catch (Exception ex)
      {
     StockLog.Write(ex.ToString());
     result = false;
      }
      return result;
 }
예제 #3
0
        private DateTime GetFtpFileTime(string filename, string path, string hostName)
        {
            if (filename == "." || filename == "..")
            {
                return(DateTime.MaxValue);
            }

            try
            {
                string        ftpurl = string.Format("ftp://{0}{1}{2}", hostName, path, filename);
                FtpWebRequest reqFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpurl));
                reqFTP.Method      = System.Net.WebRequestMethods.Ftp.GetDateTimestamp;
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new System.Net.NetworkCredential("anonymous", "");
                System.Net.FtpWebResponse response  = (System.Net.FtpWebResponse)reqFTP.GetResponse();
                System.IO.Stream          ftpStream = response.GetResponseStream();
                string fileTime = response.LastModified.ToString();
                ftpStream.Close();
                response.Close();
                return(Convert.ToDateTime(fileTime));
            }
            catch
            {
                return(DateTime.MinValue);
            }
        }
예제 #4
0
파일: FTPTest.cs 프로젝트: shakasi/coding
        public bool Test()
        {
            try
            {
                System.Net.FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(Url);
                //request.Method = CommandText; WebRequestMethods.Ftp.DeleteFile;
                request.Method      = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(UserName, Password);
                using (System.Net.FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    Console.WriteLine(response.BannerMessage.ToString());
                    Console.WriteLine(response.StatusCode.ToString());
                    Console.WriteLine(response.WelcomeMessage.ToString());
                    return(true);
                    //if (response.StatusCode == FtpStatusCode.CommandOK || response.StatusCode == FtpStatusCode.FileActionOK || response.StatusCode == FtpStatusCode.OpeningData)
                    //{

                    //    return true;
                    //}
                    //else
                    //{

                    //    return false;
                    //}
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #5
0
 /* Download File */
 public void Get(string remoteFile, string localFile)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_srvName + remoteFile);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(_srvLogin, _srvPwd);
         /* When in doubt, use these options */
         ftpRequest.UseBinary  = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive  = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Get the FTP Server's Response Stream */
         ftpStream = ftpResponse.GetResponseStream();
         /* Open a File Stream to Write the Downloaded File */
         FileStream localFileStream = new FileStream(localFile, FileMode.Create);
         /* Buffer for the Downloaded Data */
         byte[] byteBuffer = new byte[bufferSize];
         int    bytesRead  = ftpStream.Read(byteBuffer, 0, bufferSize);
         /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
         try
         {
             while (bytesRead > 0)
             {
                 localFileStream.Write(byteBuffer, 0, bytesRead);
                 bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
             }
         }
         catch (Exception e)
         {
             throw new XFTPException(500, e.Message);
         }
         /* Resource Cleanup */
         localFileStream.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (System.Net.WebException e)
     {
         if (e.Response != null)
         {
             System.Net.FtpWebResponse fwr = e.Response as System.Net.FtpWebResponse;
             if ((fwr != null) && (fwr.StatusCode == System.Net.FtpStatusCode.ActionNotTakenFileUnavailable))
             {
                 throw new XFTPException(1, e.Message);
             }
         }
         throw new XFTPException(550, e.Message);
     }
     catch (Exception e)
     {
         throw new XFTPException(501, e.Message);
     }
     return;
 }
예제 #6
0
파일: ClasseFtp.cs 프로젝트: prasist/wb20
        public bool VerificaSeExiste(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass)
        {
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath);

            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            try {
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();                
                ftpRequest = null;
                return true;
            }
            catch (Exception exc)
            {
                this.sErro = exc.Message;                
                return false;
            }
             
        }
예제 #7
0
        public static Boolean FTPRemoveDirectory()
        {
            try
            {
                sDirName = sDirName.Replace("\\", "/");
                string sURI = "FTP://" + sFTPServerIP + "/" + sDirName;
                System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI); //建立FTP連線
                //設定連線模式及相關參數
                myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord);                       //帳密驗證
                myFTP.KeepAlive   = false;                                                                        //關閉/保持 連線
                myFTP.Timeout     = 2000;                                                                         //等待時間
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.RemoveDirectory;                             //移除資料夾

                System.Net.FtpWebResponse myFtpResponse = (System.Net.FtpWebResponse)myFTP.GetResponse();         //刪除檔案/資料夾
                myFtpResponse.Close();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("FTP File Seach Fail" + "\n" + "{0}", ex.Message);
                //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                iFTPReTry--;
                if (iFTPReTry >= 0)
                {
                    return(FTPRemoveDirectory());
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #8
0
        public bool copyToServer(string remote, string local, string logPath)
        {
            bool success = false;
//            try
//            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + remote);
                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
                ftpRequest.Credentials = netCreds;

                byte[] b = File.ReadAllBytes(local);

                ftpRequest.ContentLength = b.Length;
                using (Stream s = ftpRequest.GetRequestStream())
                {
                    s.Write(b, 0, b.Length);
                }

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                // check was successful
                if (ftpResponse.StatusCode == FtpStatusCode.ClosingData)
                {
                    success = true;
                    logResult(remote, host, user, logPath);
                }
                ftpResponse.Close();
                
/*            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }*/
            return success;
        }
예제 #9
0
        public void DownloadFile(string remoteFile, string localFile)
        {
            // Создаем FTP Request
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, remoteFile));
            // Инициализируем сетевые учетные данные
            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            // Задаем команду, которая будет отправлена на FTP-сервер
            ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpRequest.Timeout = TIMEOUT;
            // Ответ FTP-сервера
            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            // Возвращаем поток данных
            ftpStream = ftpResponse.GetResponseStream();
            // Создаем локальный файл
            FileStream localFileStream = new FileStream(localFile, FileMode.Create);
            // Пишем в файл
            ftpStream.CopyTo(localFileStream);

            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
예제 #10
0
        public static int FTPGetFileSize()
        {
            try
            {
                sDirName = sDirName.Replace("\\", "/");
                string        sURI  = "FTP://" + sFTPServerIP + "/" + sDirName + "/" + sFileName;
                FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI);    //建立FTP連線
                //設定連線模式及相關參數
                myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord);               //帳密驗證
                myFTP.Timeout     = 2000;                                                                 //等待時間
                myFTP.UseBinary   = true;                                                                 //傳輸資料型別 二進位/文字
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.GetFileSize;                         //取得資料容量大小

                System.Net.FtpWebResponse myFTPFileSize = (System.Net.FtpWebResponse)myFTP.GetResponse(); //取得FTP請求回應
                return((int)myFTPFileSize.ContentLength);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("FTP File Size Query Fail" + "\n" + "{0}", ex.Message)
                //MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                iFTPReTry--;
                if (iFTPReTry >= 0)
                {
                    return(FTPGetFileSize());
                }
                else
                {
                    return(0);
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Open Ftp file in a MemoryStream for read only. The FtpStream is copied in a MemoryStream.
        /// </summary>
        /// <param name="pStream">The ouput stream.</param>
        /// <param name="connectionGroupName">The group name for the connection</param>
        private void OpenReadFtpFile(out System.IO.Stream pStream, string connectionGroupName)
        {
            pStream = null;
            try
            {
                System.Net.FtpWebRequest lRequestFileDl = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(_filePath);
                try
                {
                    lRequestFileDl.ConnectionGroupName = connectionGroupName;
                    lRequestFileDl.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                    System.Net.FtpWebResponse lResponseFileDl = (System.Net.FtpWebResponse)lRequestFileDl.GetResponse();
                    try
                    {
                        FileInfo lDestFileInfo = new FileInfo(_destRemoteFile);

                        using (System.IO.FileStream lFileStream = lDestFileInfo.OpenWrite())
                        {
                            using (System.IO.Stream lStream = lResponseFileDl.GetResponseStream())
                            {
                                int    i     = 0;
                                byte[] bytes = new byte[2048];
                                do
                                {
                                    i = lStream.Read(bytes, 0, bytes.Length);
                                    lFileStream.Write(bytes, 0, i);
                                } while (i != 0);

                                lStream.Close();
                            }
                            lFileStream.Close();
                        }

                        pStream = lDestFileInfo.OpenRead();
                        pStream.Seek(0, System.IO.SeekOrigin.Begin);
                    }
                    finally
                    {
                        lResponseFileDl.Close();
                    }
                }
                finally
                {
                    try
                    {
                        lRequestFileDl.Abort();
                    }
                    catch (NotImplementedException)
                    {
                        // Ignore the not implemented exception
                    }
                }
            }
            catch (Exception ex)
            {
                PIS.Ground.Core.LogMgmt.LogManager.WriteLog(TraceType.ERROR, ex.Message, "PIS.Ground.Core.Data.RemoteFileClass", ex, EventIdEnum.GroundCore);
            }
        }
예제 #12
0
        public string[] ListDirectory(string directory)
        {

            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(String.Format("{0}/{1}", host, directory));

            ftpRequest.Credentials = new NetworkCredential(user, pass);

            ftpRequest.UseBinary = true;
            ftpRequest.UsePassive = true;
            ftpRequest.KeepAlive = true;

            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            ftpRequest.Timeout = TIMEOUT;

            ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

            ftpStream = ftpResponse.GetResponseStream();

            StreamReader ftpReader = new StreamReader(ftpStream);

            string directoryRaw = null;

            try
            {
                while (ftpReader.Peek() != -1)
                {
                    //TODO: выдергиваем имя файла, доделать...
                    directoryRaw += ftpReader.ReadLine().Split(' ').Last() + "|";
                }
            }
            catch
            {
            }

            ftpReader.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;

            try
            {
                string[] directoryList = directoryRaw.Split("|".ToCharArray());
                return directoryList;
            }
            catch
            {
            }

            return new string[] { };
        }
예제 #13
0
        public static Boolean FTPDownloadFile()
        {
            try
            {
                sDirName = sDirName.Replace("\\", "/");
                string sURI = "FTP://" + sFTPServerIP + "/" + sDirName + "/" + sFromFileName;
                System.Net.FtpWebRequest myFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(sURI);              //建立FTP連線
                //設定連線模式及相關參數
                myFTP.Credentials = new System.Net.NetworkCredential(sUserName, sPassWord);                                    //帳密驗證
                myFTP.Timeout     = 2000;                                                                                      //等待時間
                myFTP.UseBinary   = true;                                                                                      //傳輸資料型別 二進位/文字
                myFTP.UsePassive  = false;                                                                                     //通訊埠接聽並等待連接
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.DownloadFile;                                             //下傳檔案

                System.Net.FtpWebResponse myFTPResponse = (System.Net.FtpWebResponse)myFTP.GetResponse();                      //取得FTP回應
                //下載檔案
                System.IO.FileStream myWriteStream = new System.IO.FileStream(sToFileName, FileMode.Create, FileAccess.Write); //檔案設為寫入模式
                System.IO.Stream     myReadStream = myFTPResponse.GetResponseStream();                                         //資料串流設為接收FTP回應下載
                byte[] bBuffer = new byte[2047]; int iRead = 0;                                                                //傳輸位元初始化
                do
                {
                    iRead = myReadStream.Read(bBuffer, 0, bBuffer.Length); //接收資料串流
                    myWriteStream.Write(bBuffer, 0, iRead);                //寫入下載檔案
                    //Console.WriteLine("bBuffer: {0} Byte", iRead);
                } while (!(iRead == 0));

                myReadStream.Flush();
                myReadStream.Close();
                myReadStream.Dispose();
                myWriteStream.Flush();
                myWriteStream.Close();
                myWriteStream.Dispose();
                myFTPResponse.Close();
                return(true);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("FTP Download Fail" & vbNewLine & "{0}", ex.Message)
                //MessageBox.Show(ex.Message , null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, False)
                iFTPReTry--;
                if (iFTPReTry >= 0)
                {
                    return(FTPDownloadFile());
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #14
0
 public string Load()
 {
     System.Net.FtpWebRequest request = (FtpWebRequest)System.Net.WebRequest.Create(ConfigURL);
     if (!string.IsNullOrEmpty(User))
     {
         request.Credentials = new NetworkCredential(User, PassWord);
     }
     using (System.Net.FtpWebResponse response = (FtpWebResponse)request.GetResponse())
     {
         using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
         {
             return(reader.ReadToEnd());
         }
     }
 }
예제 #15
0
        public bool Transmit(byte[] bytes)
        {
            var destAdr = ConfigurationManager.AppSettings["TransmissionDestinationAddress"];

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(destAdr);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                FtpWebResponse response = (System.Net.FtpWebResponse)(request.GetResponse());
                response.Close();
                if (response.StatusCode != FtpStatusCode.ClosingData &&
                    response.StatusCode != FtpStatusCode.CommandOK &&
                    response.StatusCode != FtpStatusCode.FileActionOK)
                {
                    _logger.LogError(response.StatusCode.ToString() + ":" + response.StatusDescription);
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (WebException e)
            {
                System.Net.FtpWebResponse ftpresp = e.Response as System.Net.FtpWebResponse;
                if (ftpresp != null)
                {
                    string status = ftpresp.StatusCode + ":" + ftpresp.StatusDescription + ":" + ftpresp.WelcomeMessage;
                    _logger.LogError("WebException: " + e.Message + " > " + status);
                }
                else
                {
                    _logger.LogError("WebException: " + e.Message);
                }

                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception: " + ex.Message);
                return(false);
            }
        }
예제 #16
0
        public static void FTPFailed(string param, string id)
        {
            string HOST_NAME        = "-";
            string USER_NAME        = "-";
            string PASSWORD         = "******";
            string HOST_NAME_FAILED = "-";

            CommonDBHelper Repo = CommonDBHelper.Instance;

            List <FTPCredential> data = Repo.GetFtpCredentialSucc(param, id, "GetFtpDownloadCredential").ToList();

            foreach (FTPCredential row in data)
            {
                HOST_NAME        = row.HOST_NAME;
                HOST_NAME_FAILED = row.HOST_NAME_FAILED;
                USER_NAME        = row.USER_NAME;
                PASSWORD         = row.PASSWORD;
            }

            NetworkCredential cred = new NetworkCredential(USER_NAME, PASSWORD);

            WebClient request = new WebClient();

            request.Credentials = new NetworkCredential(USER_NAME, PASSWORD);

            List <DirectoryItem> listing = GetDirectoryInformation(HOST_NAME, USER_NAME, PASSWORD);//"ftp://ftp.mywebsite.com/directory", "username", "password");

            string name = listing[0].Name;

            //CopyFile(HOST_NAME + name, HOST_NAME_FAILED + name, USER_NAME, PASSWORD);

            System.Net.FtpWebRequest clsRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(HOST_NAME + name);
            clsRequest.Credentials = new System.Net.NetworkCredential(USER_NAME, PASSWORD);
            clsRequest.Method      = System.Net.WebRequestMethods.Ftp.DeleteFile;

            System.Net.FtpWebResponse resp = (FtpWebResponse)clsRequest.GetResponse();
            resp.Close();

            //byte[] filedata = request.DownloadData(HOST_NAME + name); //Path.GetFileName(filename));

            //using (FileStream file = File.Create(filename + name))
            //{
            //    file.Write(filedata, 0, filedata.Length);
            //    file.Close();
            //}

            //return filename + name;
        }
예제 #17
0
        public FtpWebResponse FtpRequest(string ftprequest, string ftpmethod, string host, string ftpUsername, string ftpPassword)
        {
            System.Net.FtpWebResponse ftpwebResponse = null;
            WebException webException = null;

            try
            {
                System.Net.FtpWebRequest ftpwebrequest = (System.Net.FtpWebRequest)WebRequest.Create(ftprequest);
                ftpwebrequest.Method      = ftpmethod;
                ftpwebrequest.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                ftpwebResponse            = (FtpWebResponse)ftpwebrequest.GetResponse();
            }
            catch (WebException wex)
            {
                webException   = wex;
                ftpwebResponse = (FtpWebResponse)wex.Response;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // Catching the response out of an exception
                if (ftpwebResponse != null)
                {
                    switch (ftpwebResponse.StatusCode)
                    {
                    case FtpStatusCode.ActionNotTakenFileUnavailable:
                        // Item already exists
                        break;

                    case FtpStatusCode.PathnameCreated:
                    case FtpStatusCode.CommandOK:
                        // OK Success
                        break;

                    default:
                        if (webException != null)
                        {
                            throw webException;
                        }
                        break;
                    }
                }
            }
            return(ftpwebResponse);
        }
예제 #18
0
        //Please feel free to make the variables dynamic.
        static void Main(string[] args)
        {
            #region Creating Directory where the file will be uploaded.
            System.Net.FtpWebRequest  ftp_web_request  = null;
            System.Net.FtpWebResponse ftp_web_response = null;

            string ftp_path = ServerName + "/NewFolder";

            try
            {
                ftp_web_request             = (FtpWebRequest)WebRequest.Create(ftp_path);
                ftp_web_request.Method      = WebRequestMethods.Ftp.MakeDirectory;
                ftp_web_request.Credentials = new NetworkCredential(userName, password);

                ftp_web_response = (FtpWebResponse)ftp_web_request.GetResponse();

                string ftp_response = ftp_web_response.StatusDescription;
                string status_code  = Convert.ToString(ftp_web_response.StatusCode);

                ftp_web_response.Close();
            }
            catch (Exception Ex)
            {
                string status = Convert.ToString(Ex);

                Console.WriteLine("Failed to create folder.");
                return;
            }
            #endregion
            #region Uploading File to the directory created
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(String.Format("{0}/{1}", ftp_path, Path.GetFileName(filePath))));
            req.Method      = WebRequestMethods.Ftp.UploadFile;
            req.Credentials = new NetworkCredential(userName, password);
            Stream     ftpStream = req.GetRequestStream();
            FileStream fs        = File.OpenRead(filePath);
            byte[]     buffer    = new byte[1024];
            double     total     = (double)fs.Length;
            int        byteRead  = 0;
            do
            {
                byteRead = fs.Read(buffer, 0, 1024);
                ftpStream.Write(buffer, 0, byteRead);
            }while (byteRead != 0);
            fs.Close();
            ftpStream.Close();
            #endregion
        }
예제 #19
0
        private void WriteResponseToFile(string destPath, FtpWebResponse response, Stream responseStream)
        {
            FileStream writer = new FileStream(destPath, FileMode.Create);

            long length = response.ContentLength;
            int bufferSize = 2048;
            int readCount;
            byte[] buffer = new byte[bufferSize];

            readCount = responseStream.Read(buffer, 0, bufferSize);
            while (readCount > 0)
            {
                writer.Write(buffer, 0, readCount);
                readCount = responseStream.Read(buffer, 0, bufferSize);
            }
            writer.Close();
        }
예제 #20
0
        //二进制文件存储方法
        protected void SaveBinaryFile(FtpWebResponse response)
        {
            byte[] buffer = new byte[1024];
              string filename = convertFilename(response.ResponseUri);
              Stream outStream = File.Create(filename);
              Stream inStream = response.GetResponseStream();

              int l;
              do
              {
              l = inStream.Read(buffer, 0,
              buffer.Length);
              if (l > 0)
                  outStream.Write(buffer, 0, l);
              } while (l > 0);
              outStream.Close();
        }
예제 #21
0
 /* Create a New Directory on the FTP Server */
 public static void createDirectory(Data.RemoteServer data, string newDirectory)
 {
     /* Create an FTP Request */
     ftpRequest = (FtpWebRequest)WebRequest.Create(data.adress + newDirectory);
     /* Log in to the FTP Server with the User Name and Password Provided */
     ftpRequest.Credentials = new NetworkCredential(data.login, data.password);
     /* When in doubt, use these options */
     ftpRequest.UseBinary = true;
     ftpRequest.UsePassive = true;
     ftpRequest.KeepAlive = true;
     /* Specify the Type of FTP Request */
     ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
     /* Establish Return Communication with the FTP Server */
     ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
     /* Resource Cleanup */
     ftpResponse.Close();
     ftpRequest = null;
 }
예제 #22
0
파일: Ftp.cs 프로젝트: simul/cruise_control
 /* Delete File */
 public void delete(string deleteFile)
 {
     /* Create an FTP Request */
     ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
     /* Log in to the FTP Server with the User Name and Password Provided */
     ftpRequest.Credentials = new NetworkCredential(user, pass);
     /* When in doubt, use these options */
     ftpRequest.UseBinary = true;
     ftpRequest.UsePassive = true;
     ftpRequest.KeepAlive = true;
     /* Specify the Type of FTP Request */
     ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
     /* Establish Return Communication with the FTP Server */
     ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
     /* Resource Cleanup */
     ftpResponse.Close();
     ftpRequest = null;
 }
예제 #23
0
 /// <summary>
 /// 下載FTP檔案
 /// 存儲至Client端桌面
 /// </summary>
 /// <param name="FileName">要下載的檔案名稱</param>
 /// <returns></returns>
 public static bool Download(string FileName)
 {
     bool result = false;
     string LocalFile = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\" + FileName;
     try
     {
         Uri FtpPath = new Uri(uriServer + FileName);
         ftpRequest = (FtpWebRequest)WebRequest.Create(FtpPath);
         ftpRequest.Credentials = new NetworkCredential(UserName,Password);
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         ftpStream = ftpResponse.GetResponseStream();
         ftpFileStream = new FileStream(LocalFile, FileMode.Create);
         int BufferSize = 2048;
         byte[] byteBuffer = new byte[BufferSize];
         int bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
         try
         {
             while (bytesRead > 0)
             {
                 ftpFileStream.Write(byteBuffer, 0, bytesRead);
                 bytesRead = ftpStream.Read(byteBuffer, 0, BufferSize);
             }
             result = true;
         }
         catch (Exception ex)
         {
             sysMessage.SystemEx(ex.Message);
         }
         ftpFileStream.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (Exception ex)
     {
         sysMessage.SystemEx(ex.Message);
     }
     return result;
 }
예제 #24
0
        //**********************************************************************************************
        /// <summary>
        /// FTPサーバへファイルをアップロード
        /// </summary>
        /// <param name="s_uri">FTPサーバアドレス</param>
        /// <param name="s_user_id">ユーザーID</param>
        /// <param name="s_pass">パスワード</param>
        /// <param name="s_file_name">ファイルネーム</param>
        //**********************************************************************************************
        public void mFTP_FileUp(string s_uri, string s_user_id, string s_pass, string s_file_name)
        {
            //FtpWebRequestの作成
            System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(s_uri);
            //IDとパスワードを設定
            ftpReq.Credentials = new System.Net.NetworkCredential(s_user_id, s_pass);
            //MethodにWebRequestMethods.Ftp.UploadFile("STOR")を設定
            ftpReq.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
            //要求の完了後に接続を閉じる
            ftpReq.KeepAlive = false;
            //ASCIIモードで転送する
            //ftpReq.UseBinary = false;
            //PASVモードを無効にする
            //ftpReq.UsePassive = false;//ファイルをアップロードするためのStreamを取得
            System.IO.Stream reqStrm = ftpReq.GetRequestStream();
            //アップロードするファイルを開く
            System.IO.FileStream Fs = new System.IO.FileStream(s_file_name,
                                                               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();
            //FTPサーバーから送信されたステータスを表示
            Console.WriteLine("{0}: {1}", FtpRes.StatusCode, FtpRes.StatusDescription);
            //閉じる
            FtpRes.Close();
        }
예제 #25
0
 /* Download File */
 public void download(string remoteFile, string localFile)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Get the FTP Server's Response Stream */
         ftpStream = ftpResponse.GetResponseStream();
         /* Open a File Stream to Write the Downloaded File */
         FileStream localFileStream = new FileStream(localFile, FileMode.Create);
         /* Buffer for the Downloaded Data */
         byte[] byteBuffer = new byte[bufferSize];
         int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
         /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
         try
         {
             while (bytesRead > 0)
             {
                 localFileStream.Write(byteBuffer, 0, bytesRead);
                 bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
             }
         }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
         /* Resource Cleanup */
         localFileStream.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     return;
 }
예제 #26
0
        public void DownloadFile()
        {
            try
            {
                _destinazione = Destinazione;

                if (!(Destinazione.StartsWith("ftp://") || Destinazione.StartsWith("ftp:\\\\")))
                {
                    _destinazione = "ftp://" + Destinazione;
                }

                System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione + "/" + FileName));
                ftp.Method      = System.Net.WebRequestMethods.Ftp.DownloadFile;
                ftp.UseBinary   = true;
                ftp.Credentials = new System.Net.NetworkCredential(UserFTP, PwdFTP);


                ftp             = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(new Uri(_destinazione + "/" + FileName));
                ftp.Method      = System.Net.WebRequestMethods.Ftp.DownloadFile;
                ftp.UseBinary   = true;
                ftp.Credentials = new System.Net.NetworkCredential(UserFTP, PwdFTP);

                ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse();
                Stream       responseStream        = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);



                using (StreamWriter writer = new StreamWriter(FilePath))
                {
                    writer.Write(reader.ReadToEnd());
                }

                reader.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #27
0
파일: Ftp.cs 프로젝트: obritto/FTPApp
        /* Delete File */
        public void Delete(string deleteFile)
        {
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + deleteFile);
                ftpRequest.Credentials = new NetworkCredential(user, pass);

                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return;
        }
예제 #28
0
 // actually the only useful function in project.
 public DateTime GetFtpFileTime(string filename)
 {
     try
     {
         FtpWebRequest reqFTP = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(filename));
         reqFTP.Method      = System.Net.WebRequestMethods.Ftp.GetDateTimestamp;
         reqFTP.UseBinary   = true;
         reqFTP.Credentials = new System.Net.NetworkCredential(this.Username, this.Password);
         System.Net.FtpWebResponse response  = (System.Net.FtpWebResponse)reqFTP.GetResponse();
         System.IO.Stream          ftpStream = response.GetResponseStream();
         string fileTime = response.LastModified.ToString();
         ftpStream.Close();
         response.Close();
         return(Convert.ToDateTime(fileTime));
     }
     catch/* (Exception ex)*/
     {
         return(DateTime.MinValue);
     }
 }
예제 #29
0
        public static bool FTPDeleteFile()
        {
            try
            {
                //DirName = DirName.Replace("\\", "/");
                //string sURI = "FTP://" + FTPServerIP + "/" + DirName + FileName;
                string sURI = GetFTPURL();
                System.Net.FtpWebRequest myFTP = (FtpWebRequest)WebRequest.Create(sURI); //建立FTP連線

                //設定連線模式及相關參數
                myFTP.EnableSsl = EnabledSSL;   //設定是否使用安全連線

                if (EnabledSSL)
                {
                    ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;
                }

                myFTP.Credentials = new System.Net.NetworkCredential(UserName, PassWord);      //帳密驗證
                myFTP.KeepAlive   = false;                                                     //關閉/保持 連線
                myFTP.Timeout     = 2000;                                                      //等待時間
                myFTP.Method      = System.Net.WebRequestMethods.Ftp.DeleteFile;               //刪除檔案

                System.Net.FtpWebResponse myFtpResponse = (FtpWebResponse)myFTP.GetResponse(); //刪除檔案/資料夾
                myFtpResponse.Close();
                return(true);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("FTP File Seach Fail" + "\n" + "{0}", ex.Message);
                //MessageBox.Show(ex.Message , null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly, false);
                FTPReTry--;
                if (FTPReTry >= 0)
                {
                    return(FTPDeleteFile());
                }
                else
                {
                    return(false);
                }
            }
        }
예제 #30
0
파일: MyFtp.cs 프로젝트: Yowe/src
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="remoteFile"></param>
        /// <returns></returns>
        public byte[] DownloadFile(string remoteFile)
        {
            this.Connect("ftp://" + this._serverIP + "/" + remoteFile);
            this.ftpRequest.Method = "RETR";

            using (this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse())
            {
                using (this.ftpStream = this.ftpResponse.GetResponseStream())
                {
                    byte[] byteBuffer = new byte[this.bufferSize];
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        for (int bytesRead = this.ftpStream.Read(byteBuffer, 0, this.bufferSize); bytesRead > 0; bytesRead = this.ftpStream.Read(byteBuffer, 0, this.bufferSize))
                        {
                            memoryStream.Write(byteBuffer, 0, bytesRead);
                        }
                        return memoryStream.Length > 0 ? memoryStream.ToArray() : null;
                    }
                }
            }
        }
예제 #31
0
 public void EliminarArchivo(string ArchivoEliminar)
 {
     try
     {
         Console.WriteLine("Iniciando proceso de eliminacion de archivo iniciado.");
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Direccion + "/" + ArchivoEliminar);
         ftpRequest.Credentials = new NetworkCredential(Usuario, Password);
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         Console.WriteLine("Archivo eliminado correctamente.");
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (Exception)
     {
         Console.WriteLine("No se encuentra el archivo a eliminar");
     }
 }
        public List <string> GetListOfExistingFilesNames()
        {
            System.Net.FtpWebRequest ftpRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(ftpServerPath);
            ftpRequest.Credentials = new System.Net.NetworkCredential(userId, password);
            ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
            System.Net.FtpWebResponse response     = (System.Net.FtpWebResponse)ftpRequest.GetResponse();
            System.IO.StreamReader    streamReader = new System.IO.StreamReader(response.GetResponseStream());

            List <string> directories = new List <string>();

            string line = streamReader.ReadLine();

            while (!string.IsNullOrEmpty(line))
            {
                directories.Add(line);
                line = streamReader.ReadLine();
            }

            streamReader.Close();
            return(directories);
        }
예제 #33
0
        //Sorts the files and only shows the files you want.
        public List<String> listFiles(FtpWebResponse files, Boolean showAllFiles)
        {
            Stream responseStream = files.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            String filesFolders = reader.ReadToEnd();

            List<String> fileArray = filesFolders.Split('\n').ToList<String>();
            List<String> newList = new List<string>();

            if (!showAllFiles)
            {
                foreach (String s in fileArray)
                {
                    if (s.Contains(".mp3") || s.StartsWith("d")) //Feel free to add the filetypes you like.
                    {
                        if (s.Length > 0)
                        {
                            Char[] c = s.ToCharArray();
                            for (int i = 0; i < c.Length; i++)
                            {
                                if (c[i] == ':')
                                {
                                    newList.Add(s.Substring(i + 4));
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                foreach (String s in fileArray)
                {
                    newList.Add(s); //Adds all directorydetails
                }
            }
            newList.Sort();
            return newList;
        }
예제 #34
0
        // Create Directory
        public void createRemoteDirectory(string newDirectory)
        {
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
                ftpRequest.Credentials = new NetworkCredential(user,pass);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;

                ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpResponse.Close();
                ftpRequest = null;
            }
            catch(Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
예제 #35
0
        public string DescargaArchivo(string ArchivoFTP, string ArchivoLocal)
        {
            try
            {
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(Direccion + "/" + ArchivoFTP);
                ftpRequest.Credentials = new NetworkCredential(Usuario, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;

                Console.WriteLine("Iniciando proceso de Descarga de Archivo.");
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpStream = ftpResponse.GetResponseStream();
                FileStream ArchivoDescargado = new FileStream(ArchivoLocal, FileMode.Create);
                byte[] byteBuffer = new byte[2048];
                int bytesRead = ftpStream.Read(byteBuffer, 0, 2048);

                while (bytesRead > 0)
                {
                    ArchivoDescargado.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
                }

                Console.WriteLine("Proceso de Descarga Finalizado.");
                EliminarArchivo(ArchivoFTP);
                ArchivoDescargado.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
                return "Exito";
            }
            catch (Exception)
            {
                Console.WriteLine("No se encuentra el archivo para descargar");
                return "Error";
            }
        }
예제 #36
0
        public bool Transmit(byte[] bytes)
        {
            try
            {
                var result = UploadData(bytes);
                if (result.StatusCode != FtpStatusCode.ClosingData &&
                    result.StatusCode != FtpStatusCode.CommandOK &&
                    result.StatusCode != FtpStatusCode.FileActionOK)
                {
                    _logger.LogError(result.StatusCode.ToString() + ":" + result.StatusDescription);
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            catch (WebException e)
            {
                System.Net.FtpWebResponse ftpresp = e.Response as System.Net.FtpWebResponse;
                if (ftpresp != null)
                {
                    string status = ftpresp.StatusCode + ":" + ftpresp.StatusDescription + ":" + ftpresp.WelcomeMessage;
                    _logger.LogError("WebException: " + e.Message + " > " + status);
                }
                else
                {
                    _logger.LogError("WebException: " + e.Message);
                }

                return(false);
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception: " + ex.Message);
                return(false);
            }
        }
예제 #37
0
파일: FTPTools.cs 프로젝트: Danand/Bytloos
        /// <summary>
        /// Creates remote directory.
        /// </summary>
        /// <param name="relativePath">Directory path.</param>
        public void CreateDirectory(string relativePath)
        {
            try
            {
                this.request = (FtpWebRequest)WebRequest.Create(string.Format("{0}/{1}", host, relativePath));

                this.request.Credentials = new NetworkCredential(username, password);
                this.request.UseBinary = true;
                this.request.UsePassive = true;
                this.request.KeepAlive = true;
                this.request.Method = WebRequestMethods.Ftp.MakeDirectory;

                this.response = (FtpWebResponse)this.request.GetResponse();

                this.response.Close();

                this.request = null;
            }
            catch (Exception exception)
            {
                this.exceptions.Add(exception);
            }
        }
예제 #38
0
        // Delete File
        public void delete(string filePath)
        {
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + filePath);

                ftpRequest.Credentials = new NetworkCredential(user, pass);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;

                ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return;
        }
예제 #39
0
 /* Delete File */
 public void Delete(string deleteFile)
 {
     try
     {
         /* Create an FTP Request */
         _ftpRequest = (FtpWebRequest)WebRequest.Create(_host + "/" + deleteFile);
         /* Log in to the FTP Server with the User Name and Password Provided */
         _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
         /* When in doubt, use these options */
         _ftpRequest.UseBinary = true;
         _ftpRequest.UsePassive = true;
         _ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         _ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
         /* Establish Return Communication with the FTP Server */
         _ftpResponse = (FtpWebResponse)_ftpRequest.GetResponse();
         /* Resource Cleanup */
         _ftpResponse.Close();
         _ftpRequest = null;
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     return;
 }
예제 #40
0
파일: FTP.cs 프로젝트: lxh2014/gigade-net
 /// <summary>
 /// 创建文件夹
 /// </summary>
 public void MakeDirectory()
 {
     ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
     try
     {
         response = (FtpWebResponse)ftpRequest.GetResponse();
     }
     catch (Exception ex)
     {
         if (ex.Message.IndexOf("550") < 0)
         {
             throw ex;
         }
         //throw ex;
     }
     finally
     {
         if (response != null)
         {
             response.Close();
         }
     }
 }
예제 #41
0
        //Format a message from a System.Net.WebException instance
        public static string getWebExceptionMessage(Exception ex)
        {
            string message = String.Empty;

            //Attempt to cast the input Exception instance...
            System.Net.WebException webex = ex as System.Net.WebException;
            if (null != webex)
            {
                //Success - format message...
                //ASSUMPTION - Status value always exists...
                message = webex.Status.GetEnumDescription();

                if (null != webex.Response)
                {
                    //Response exists - retrieve per type...
                    System.Net.HttpWebResponse httpres = webex.Response as System.Net.HttpWebResponse;
                    if (null != httpres)
                    {
                        //Http Response...
                        message = String.Format("{0} : {1}", ((int)httpres.StatusCode).ToString(), httpres.StatusDescription);
                    }
                    else
                    {
                        System.Net.FtpWebResponse ftpres = webex.Response as System.Net.FtpWebResponse;
                        if (null != ftpres)
                        {
                            //Ftp Response...
                            message = String.Format("{0 (ftp)} : {1}", ((int)ftpres.StatusCode).ToString(), ftpres.StatusDescription);
                        }
                    }
                }
            }

            //Processing complete - return message
            return(message);
        }
예제 #42
0
파일: ClasseFtp.cs 프로젝트: prasist/wb20
        public bool DownloadFileFTP(string destinfilepath, string ftphost, string ftpfilepath, string user, string pass)
        {
            try
            {

                ftpRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftphost + "//" + ftpfilepath);             
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpRequest.Credentials = new NetworkCredential(user, pass);             
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;                             
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();             
                ftpStream = ftpResponse.GetResponseStream();                
                FileStream localFileStream = new FileStream(destinfilepath, FileMode.Create);
                
                byte[] byteBuffer = new byte[bufferSize];
                int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                
                while (bytesRead > 0)
                {
                    localFileStream.Write(byteBuffer, 0, bytesRead);
                    bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                }
                
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
                return true;

            }
            catch (Exception erro)
            {
                throw new Exception(erro.Message);                
            }
        }
예제 #43
0
        private bool ExecuteSimpleFtpWebRequest(FtpWebRequest ftpRequest)
        {
            bool result = false;
            try
            {
                LogStepFtpRequest(ftpRequest.RequestUri, ftpRequest.Method);
                LastResponse = (FtpWebResponse)ftpRequest.GetResponse();
                TestEasyLog.Instance.Info(string.Format("FTP request completed: {0} - {1}", LastResponse.StatusCode, LastResponse.StatusDescription));
                result = true;
            }
            catch (WebException ex)
            {
                TestEasyLog.Instance.Failure(string.Format("Exception while getting response: '{0}'", ex.Message));
                LastResponse = (FtpWebResponse)ex.Response;
            }
            catch (Exception ex2)
            {
                TestEasyLog.Instance.Failure(string.Format("Exception while getting response: '{0}'", ex2.Message));
            }
            finally
            {
                if (LastResponse != null)
                {
                    LastResponse.Close();
                }
            }

            return result;
        }
예제 #44
0
        private string GetStringFromResponseStream(FtpWebRequest ftpRequest)
        {
            string result = null;

            var memoryStream = new MemoryStream();
            StreamReader streamReader = null;

            try
            {
                LastResponse = (FtpWebResponse)ftpRequest.GetResponse();
                var responseStream = LastResponse.GetResponseStream();

                if (TransferData(responseStream, memoryStream))
                {
                    streamReader = new StreamReader(memoryStream);
                    memoryStream.Position = 0L;
                    result = streamReader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                TestEasyLog.Instance.Info(string.Format("Exception while getting response for '{0}'. Message: '{1}'", ftpRequest.RequestUri, ex.Message));
                LastResponse = (FtpWebResponse)ex.Response;
            }
            catch (InvalidOperationException ex2)
            {
                TestEasyLog.Instance.Info(string.Format("Exception while getting response for '{0}'. Message: '{1}'", ftpRequest.RequestUri, ex2.Message));
            }
            finally
            {
                if (LastResponse != null)
                {
                    LastResponse.Close();
                }

                memoryStream.Close();

                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }

            return result;
        }
예제 #45
0
        private DateTime GetDateLastModified(string targetPath)
        {
            var lastModified = default(DateTime);
            var ftpWebRequest = GetFtpWebRequest(targetPath);
            ftpWebRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp;
            
            LogStepFtpRequest(ftpWebRequest.RequestUri, string.Format("{0} {1}", ftpWebRequest.Method, targetPath));

            try
            {
                LastResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                lastModified = LastResponse.LastModified;
            }
            catch (WebException ex)
            {
                TestEasyLog.Instance.Failure(string.Format("Exception while getting FTP response: '{0}'", ex.Message));
                LastResponse = (FtpWebResponse)ex.Response;
            }
            catch (InvalidOperationException ex2)
            {
                TestEasyLog.Instance.Failure(string.Format("Exception while getting FTP response: '{0}'", ex2.Message));
            }
            finally
            {
                if (LastResponse != null)
                {
                    LastResponse.Close();
                }
            }

            return lastModified;
        }
예제 #46
0
        /// <summary>
        /// 下载FTP文件
        /// </summary>
        /// <param name="part"></param>
        void DownloadFTPFile(string key, FTPItem part, double filesize)
        {
            try
            {
                //下载文件的URI
                Uri u = new Uri(part.ServerFilePath);
                //设定下载文件的保存路径
                string downFile = part.LocFilePath;



                //FtpWebRequest的作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(u);

                //设定用户名和密码

                ftpReq.Credentials = new System.Net.NetworkCredential(FTPUser, FTPPassword);

                //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定

                ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;

                //要求终了后关闭连接
                ftpReq.KeepAlive = false;

                //使用ASCII方式传送
                ftpReq.UseBinary = false;

                //设定PASSIVE方式无效
                ftpReq.UsePassive = false;



                //判断是否继续下载
                //继续写入下载文件的FileStream
                System.IO.FileStream fs;
                if (part.IsContinue)
                {
                    if (System.IO.File.Exists(downFile))
                    {
                        //继续下载
                        ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;
                        fs = new System.IO.FileStream(downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                    }

                    else
                    {
                        //一般下载
                        fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                    }
                }
                else
                {
                    if (System.IO.File.Exists(downFile))
                    {
                        File.Delete(downFile);
                    }
                    //一般下载
                    fs = new System.IO.FileStream(downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                }



                //取得FtpWebResponse
                System.Net.FtpWebResponse ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();

                //为了下载文件取得Stream
                System.IO.Stream resStrm = ftpRes.GetResponseStream();

                //写入下载的数据
                byte[] buffer = new byte[20480];

                double posLen = 0;
                while (part.CloseState == false && part.RunState == FTPRunState.Run)
                {
                    int readSize = resStrm.Read(buffer, 0, buffer.Length);
                    posLen += readSize;
                    if (readSize == 0)
                    {
                        break;
                    }

                    fs.Write(buffer, 0, readSize);

                    if (OnProgressChanged != null)
                    {
                        //System.Threading.Tasks.Task.Factory.StartNew(() =>
                        //{
                        OnProgressChanged(key, Math.Round((posLen / filesize) * 100, 2));
                        //});
                    }
                }
                fs.Close();
                resStrm.Close();

                if (part.RunState == FTPRunState.Run)
                {
                    UploadFileList.TryRemove(key, out part);
                    if (OnProgressChanged != null)
                    {
                        OnProgressChanged(key, 100.00);
                    }

                    if (OnCompleted != null)
                    {
                        OnCompleted(key, part.ServerFilePath);
                    }
                }


                //表示从FTP服务器被送信的状态
                //Console.WriteLine("{0}: {1}", ftpRes.StatusCode, ftpRes.StatusDescription);

                //关闭连接
                ftpRes.Close();
            }
            catch (Exception ex)
            {
                part.RunState = FTPRunState.Error;
                UploadFileList.TryRemove(key, out part);//出错则删除
                OnFailed(key, 150);
            }
        }
예제 #47
0
        /// <summary>
        /// 从FTP下载文件到本地服务器,支持断点下载
        /// </summary>
        /// <param name="ftpUri">ftp文件路径,如"ftp://localhost/test.txt"</param>
        /// <param name="saveFile">保存文件的路径,如C:\\test.txt</param>
        public void BreakPointDownLoadFile(string ftpUri, string saveFile)
        {
            System.IO.FileStream      fs      = null;
            System.Net.FtpWebResponse ftpRes  = null;
            System.IO.Stream          resStrm = null;
            try
            {
                //下载文件的URI
                Uri u = new Uri(ftpUri);
                //设定下载文件的保存路径
                string downFile = saveFile;

                //FtpWebRequest的作成
                System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)
                                                  System.Net.WebRequest.Create(u);
                //设定用户名和密码
                ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord);
                //MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定
                ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
                //要求终了后关闭连接
                ftpReq.KeepAlive = false;
                //使用ASCII方式传送
                ftpReq.UseBinary = false;
                //设定PASSIVE方式无效
                ftpReq.UsePassive = false;

                //判断是否继续下载
                //继续写入下载文件的FileStream

                if (System.IO.File.Exists(downFile))
                {
                    //继续下载
                    ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;
                    fs = new System.IO.FileStream(
                        downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                }
                else
                {
                    //一般下载
                    fs = new System.IO.FileStream(
                        downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                }

                //取得FtpWebResponse
                ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();
                //为了下载文件取得Stream
                resStrm = ftpRes.GetResponseStream();
                //写入下载的数据
                byte[] buffer = new byte[1024];
                while (true)
                {
                    int readSize = resStrm.Read(buffer, 0, buffer.Length);
                    if (readSize == 0)
                    {
                        break;
                    }
                    fs.Write(buffer, 0, readSize);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpUri + "异常信息:" + ex.ToString());
            }
            finally
            {
                fs.Close();
                resStrm.Close();
                ftpRes.Close();
            }
        }
예제 #48
0
        public string  File_List_Remote_Computer()
        {
            try
            {
                // I set the Ip address of the remote computer
                string IpAddress = "";
                IpAddress = this.host;

                // I set the credentials of the remote computer.
                string UserName     = this.user;
                string UserPassword = this.password;

                // I set the Ftp object.
                System.Net.FtpWebRequest FtpWebRequest = (System.Net.FtpWebRequest)System.Net.WebRequest.Create(IpAddress);
                FtpWebRequest.Credentials = new System.Net.NetworkCredential(UserName, UserPassword);
                FtpWebRequest.Method      = System.Net.WebRequestMethods.Ftp.ListDirectory;
                FtpWebRequest.Proxy       = null;
                System.Net.FtpWebResponse FtpWebResponse = (System.Net.FtpWebResponse)FtpWebRequest.GetResponse();

                // I set the StreamReader object.
                // It will contain the file list of the remote computer
                System.IO.StreamReader StreamReader = new System.IO.StreamReader
                                                          (FtpWebResponse.GetResponseStream(), System.Text.Encoding.ASCII);

                // I set the DataFound variable.
                bool DataFound = false;

                // I set FileName variable.
                string FileName = "";


                // I loop on the StreamReader object.
                while (StreamReader.EndOfStream == false)
                {
                    System.IO.FileStream sr = new System.IO.FileStream(host + "/" + FileName, System.IO.FileMode.Open);

                    DataFound = true;

                    FileName = StreamReader.ReadLine().ToString();

                    return(FileName + "|" + sr.Length);
                }

                // If the value of the DataFound variable is
                // False then no data was found.
                if (DataFound == false)
                {
                    return("No data found.");
                }

                // I close the objects.
                StreamReader.Close();
                FtpWebResponse.Close();
                FtpWebRequest = null;

                return("");
            }
            catch (Exception ex)
            {
                // I show an error message if the sub generates an error.
                if (ex.Message.Contains("(530)"))
                {
                    return("User name or password is wrong.");
                }
                else
                {
                    return("Error message: " + ex.Message);
                }
            }
        }
        public void Exec(Int32 ImageSend)
        {
            try
            {
                Model.Local.ArticleImageRepository ArticleImageRepository = new Model.Local.ArticleImageRepository();
                if (ArticleImageRepository.ExistPre_Id(ImageSend) == false)
                {
                    Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository();
                    Model.Prestashop.PsImage           PsImage           = PsImageRepository.ReadImage(Convert.ToUInt32(ImageSend));
                    Model.Local.ArticleRepository      ArticleRepository = new Model.Local.ArticleRepository();
                    if (ArticleRepository.ExistPre_Id(Convert.ToInt32(PsImage.IDProduct)))
                    {
                        Model.Local.Article Article = ArticleRepository.ReadPre_Id(Convert.ToInt32(PsImage.IDProduct));

                        Model.Prestashop.PsImageLangRepository PsImageLangRepository = new Model.Prestashop.PsImageLangRepository();
                        if (PsImageLangRepository.ExistImageLang(Convert.ToUInt32(ImageSend), Core.Global.Lang))
                        {
                            string extension = Core.Img.jpgExtension;
                            String FTP       = Core.Global.GetConfig().ConfigFTPIP;
                            String User      = Core.Global.GetConfig().ConfigFTPUser;
                            String Password  = Core.Global.GetConfig().ConfigFTPPassword;

                            Model.Prestashop.PsImageLang PsImageLang  = PsImageLangRepository.ReadImageLang(Convert.ToUInt32(ImageSend), Core.Global.Lang);
                            Model.Local.ArticleImage     ArticleImage = new Model.Local.ArticleImage()
                            {
                                ImaArt_Name       = (!String.IsNullOrEmpty(PsImageLang.Legend)) ? PsImageLang.Legend : Article.Art_Ref,
                                ImaArt_Position   = PsImage.Position,
                                ImaArt_Default    = Convert.ToBoolean(PsImage.Cover),
                                Pre_Id            = Convert.ToInt32(PsImage.IDImage),
                                Art_Id            = Article.Art_Id,
                                ImaArt_Image      = string.Empty,
                                ImaArt_SourceFile = SearchFreeNameFile(Article.Art_Id, Article.Art_Ref, extension),
                                ImaArt_DateAdd    = DateTime.Now
                            };
                            ArticleImageRepository.Add(ArticleImage);

                            Boolean import_img = false;
                            try
                            {
                                // <JG> 10/04/2013 gestion système d'images
                                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

                                    foreach (char directory in PsImage.IDImage.ToString())
                                    {
                                        ftpPath += directory + "/";
                                    }
                                    break;
                                    #endregion
                                }

                                // <JG> 21/05/2013 import image originale
                                Boolean import_img_tmp = false;
                                try
                                {
                                    string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                        ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + Core.Img.jpgExtension
                                        : FTP + ftpPath + PsImage.IDImage + Core.Img.jpgExtension;

                                    bool existfile = Core.Ftp.ExistFile(ftpfullpath, User, Password);
                                    if (existfile)
                                    {
                                        System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                        ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                                        ftp.UseBinary   = true;
                                        ftp.UsePassive  = true;
                                        ftp.KeepAlive   = false;
                                        ftp.EnableSsl   = Core.Global.GetConfig().ConfigFTPSSL;

                                        System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse();
                                        Stream reader = response.GetResponseStream();

                                        MemoryStream memStream      = new MemoryStream();
                                        byte[]       buffer         = new byte[1024];
                                        byte[]       downloadedData = new byte[0];
                                        while (true)
                                        {
                                            int bytesRead = reader.Read(buffer, 0, buffer.Length);
                                            if (bytesRead != 0)
                                            {
                                                memStream.Write(buffer, 0, bytesRead);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                            downloadedData = memStream.ToArray();
                                        }

                                        string target_folder = (Core.Global.GetConfig().ConfigLocalStorageMode == Parametres.LocalStorageMode.simple_system)
                                            ? Global.GetConfig().Folders.TempArticle
                                            : ArticleImage.advanced_folder;

                                        if (downloadedData != null && downloadedData.Length != 0)
                                        {
                                            FileStream newFile = new FileStream(
                                                System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id)),
                                                FileMode.Create);
                                            newFile.Write(downloadedData, 0, downloadedData.Length);
                                            newFile.Close();
                                            newFile.Dispose();
                                            memStream.Dispose();
                                            downloadedData = new byte[0];
                                        }
                                        string local_file_tmp = System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id));

                                        // <JG> 30/09/2013 détection encodage PNG lors de l'import
                                        Boolean rename_to_png    = false;
                                        System.Drawing.Image img = System.Drawing.Image.FromFile(local_file_tmp);
                                        var imgguid = img.RawFormat.Guid;
                                        img.Dispose();
                                        System.Drawing.Imaging.ImageCodecInfo search;
                                        foreach (System.Drawing.Imaging.ImageCodecInfo codec in System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders())
                                        {
                                            if (codec.FormatID == imgguid)
                                            {
                                                search = codec;
                                                if (search.FormatDescription == "PNG")
                                                {
                                                    rename_to_png = true;
                                                }
                                                break;
                                            }
                                        }
                                        if (rename_to_png)
                                        {
                                            if (System.IO.File.Exists(local_file_tmp))
                                            {
                                                extension = Core.Img.pngExtension;
                                                System.IO.File.Move(local_file_tmp, System.IO.Path.Combine(target_folder, String.Format("{0}" + extension, ArticleImage.ImaArt_Id)));
                                            }
                                            ArticleImage.ImaArt_SourceFile = SearchFreeNameFile(Article.Art_Id, Article.Art_Ref, extension);
                                        }
                                        ArticleImage.ImaArt_Image = String.Format("{0}" + extension, ArticleImage.ImaArt_Id);
                                        ArticleImageRepository.Save();

                                        Core.Img.resizeImage(new System.Drawing.Bitmap(ArticleImage.TempFileName),
                                                             Core.Global.GetConfig().ConfigImageMiniatureWidth,
                                                             Core.Global.GetConfig().ConfigImageMiniatureHeight,
                                                             ArticleImage.SmallFileName);
                                        import_img_tmp = true;
                                    }
                                }
                                catch (Exception)
                                {
                                    // Not implemented
                                }
                                if (import_img_tmp)
                                {
                                    Model.Prestashop.PsImageTypeRepository PsImageTypeRepository = new Model.Prestashop.PsImageTypeRepository();
                                    List <Model.Prestashop.PsImageType>    ListPsImageType       = PsImageTypeRepository.ListProduct(1);
                                    foreach (Model.Prestashop.PsImageType PsImageType in ListPsImageType)
                                    {
                                        string ftpfullpath = (Core.Global.GetConfig().ConfigImageStorageMode == Core.Parametres.ImageStorageMode.old_system)
                                            ? FTP + ftpPath + PsImage.IDProduct + "-" + PsImage.IDImage + "-" + PsImageType.Name + Core.Img.jpgExtension
                                            : FTP + ftpPath + PsImage.IDImage + "-" + PsImageType.Name + Core.Img.jpgExtension;

                                        System.Net.FtpWebRequest ftp = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(ftpfullpath);
                                        ftp.Credentials = new System.Net.NetworkCredential(User, Password);
                                        ftp.UseBinary   = true;
                                        ftp.UsePassive  = true;
                                        ftp.KeepAlive   = false;
                                        ftp.EnableSsl   = Core.Global.GetConfig().ConfigFTPSSL;

                                        System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)ftp.GetResponse();
                                        Stream reader = response.GetResponseStream();

                                        MemoryStream memStream      = new MemoryStream();
                                        byte[]       buffer         = new byte[1024];
                                        byte[]       downloadedData = new byte[0];
                                        while (true)
                                        {
                                            int bytesRead = reader.Read(buffer, 0, buffer.Length);
                                            if (bytesRead != 0)
                                            {
                                                memStream.Write(buffer, 0, bytesRead);
                                            }
                                            else
                                            {
                                                break;
                                            }
                                            downloadedData = memStream.ToArray();
                                        }

                                        if (downloadedData != null && downloadedData.Length != 0)
                                        {
                                            FileStream newFile = new FileStream(ArticleImage.FileName(PsImageType.Name), FileMode.Create);
                                            newFile.Write(downloadedData, 0, downloadedData.Length);
                                            newFile.Close();
                                        }
                                    }
                                    import_img = true;

                                    // gestion image par défaut
                                    if (ArticleImage.ImaArt_Default)
                                    {
                                        List <Model.Local.ArticleImage> ListArticleImage = ArticleImageRepository.ListArticle(ArticleImage.Art_Id.Value);
                                        if (ListArticleImage.Count(i => i.ImaArt_Default == true && i.ImaArt_Id != ArticleImage.ImaArt_Id) > 0)
                                        {
                                            foreach (Model.Local.ArticleImage ArticleImageDefault in ListArticleImage.Where(i => i.ImaArt_Default == true && i.ImaArt_Id != ArticleImage.ImaArt_Id))
                                            {
                                                ArticleImageDefault.ImaArt_Default = false;
                                                ArticleImageRepository.Save();
                                            }
                                        }
                                    }

                                    // liens images déclinaisons
                                    ExecAttributeImage(PsImage, ArticleImage);
                                }
                            }
                            catch (Exception ex)
                            {
                                Core.Error.SendMailError("[DOWNLOAD FTP IMAGE ARTICLE]<br />" + ex.ToString());
                                ArticleImageRepository.Delete(ArticleImage);
                            }
                            if (!import_img)
                            {
                                ArticleImageRepository.Delete(ArticleImage);
                            }
                        }
                    }
                }
                else if (ArticleImageRepository.ExistPrestaShop(ImageSend))
                {
                    // import des affectations aux déclinaisons
                    Model.Prestashop.PsImageRepository PsImageRepository = new Model.Prestashop.PsImageRepository();
                    Model.Prestashop.PsImage           PsImage           = PsImageRepository.ReadImage(Convert.ToUInt32(ImageSend));
                    Model.Local.ArticleImage           ArticleImage      = ArticleImageRepository.ReadPrestaShop(ImageSend);
                    ExecAttributeImage(PsImage, ArticleImage);
                }
            }
            catch (Exception ex)
            {
                Core.Error.SendMailError(ex.ToString());
            }
        }
예제 #50
0
 /* Get the Size of a File */
 public string getFileSize(string fileName)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + fileName);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Establish Return Communication with the FTP Server */
         ftpStream = ftpResponse.GetResponseStream();
         /* Get the FTP Server's Response Stream */
         StreamReader ftpReader = new StreamReader(ftpStream);
         /* Store the Raw Response */
         string fileInfo = null;
         /* Read the Full Response Stream */
         try { while (ftpReader.Peek() != -1) { fileInfo = ftpReader.ReadToEnd(); } }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
         /* Resource Cleanup */
         ftpReader.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
         /* Return File Size */
         return fileInfo;
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     /* Return an Empty string Array if an Exception Occurs */
     return "";
 }
예제 #51
0
 /* Rename File */
 public void rename(string currentFileNameAndPath, string newFileName)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + currentFileNameAndPath);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.Rename;
         /* Rename the File */
         ftpRequest.RenameTo = newFileName;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Resource Cleanup */
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     return;
 }
예제 #52
0
        /// <summary>
        /// amocmebs CSV fails, aris tu ara axali gadacemis chanaceri
        /// </summary>
        /// <returns>abrunebs true-s tu axali gadacema daicko, tuarada false-s.</returns>
        public static bool nextCSVResult(out string sShemdegiGadacemisSaxeli
                                         , out DateTime dtAxaliGadacemisDackebisDro)
        {
            //string[] lsAllLines = File.ReadAllLines(File.ReadAllText(VideoCaptureController.sFileContainingInfoAboutCSVFilePath));

            FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://92.241.90.13/" + "OAStudioLog"
                                                                    + DateTime.Now.Year.ToString()
                                                                    + RecorderController.add_zeros(DateTime.Now.Month.ToString())
                                                                    + RecorderController.add_zeros(DateTime.Now.Day.ToString())
                                                                    + ".csv");

            ftp.Credentials = new NetworkCredential("log", "log");
            ftp.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);//nocachenostore?
            try
            {
                System.Net.FtpWebResponse resp = (FtpWebResponse)ftp.GetResponse();
                StreamReader csv = new StreamReader(resp.GetResponseStream(), Encoding.ASCII);
                //
                string[] lsAllLines = csv.ReadToEnd().Replace("\r", "").Split('\n');
                //
                int lastValidLineNum = lsAllLines.Length - 1;
                while ("" == lsAllLines[lastValidLineNum] ||
                       lsAllLines[lastValidLineNum].Split(',').Length < 7 ||
                       "On Air Studio terminated" == lsAllLines[lastValidLineNum].Split(',')[6] ||
                       (lsAllLines[lastValidLineNum].Split(',').Length > 7 && "Playback Stopped" == lsAllLines[lastValidLineNum].Split(',')[7]) ||
                       !(lsAllLines[lastValidLineNum].LastIndexOf(',') > lsAllLines[lastValidLineNum].IndexOf(',')) ||
                       !("RED" == lsAllLines[lastValidLineNum].Split(',')[1] || "PLAY" == lsAllLines[lastValidLineNum].Split(',')[1] || "NEWS PLAY" == lsAllLines[lastValidLineNum].Split(',')[1])
                       )
                {
                    if (0 > lastValidLineNum)
                    {
                        Console.WriteLine("CSV File not valid. Press any key to exit!");
                        Console.ReadLine();
                        Application.Exit();
                        break;
                    }
                    lastValidLineNum--;
                }
                if (lsAllLines.Length > unLineCountLastTime &&
                    sGadacemisSaxeliLastTime != lsAllLines[lastValidLineNum].Split(',')[4])
                {
                    unLineCountLastTime = lsAllLines.Length;
                    string[] arrBoloStriqonisMonacemebi = lsAllLines[lastValidLineNum].Split(',');
                    sGadacemisSaxeliLastTime = TrimFileNameFromUnwantedChars(arrBoloStriqonisMonacemebi[4]);
                    //todo guess name from arrBoloStriqonisMonacemebi[4]
                    sShemdegiGadacemisSaxeli
                        = TrimFileNameFromUnwantedChars(
                              arrBoloStriqonisMonacemebi[4].Substring(arrBoloStriqonisMonacemebi[4].LastIndexOf('\\') + 1));
                    try
                    {
                        dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6]
                                                                          //, @"dd\/M\/yyyy HH:mm:ss"
                                                                          , @"M\/d\/yyyy HH:mm:ss"
                                                                          //was dd
                                                                          , CultureProvider);
                        if (dtAxaliGadacemisDackebisDro.Month != DateTime.Now.Month)
                        {
                            dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6]
                                                                              //, @"dd\/M\/yyyy HH:mm:ss"
                                                                              , @"d\/M\/yyyy HH:mm:ss"
                                                                              , CultureProvider);
                        }
                    }
                    catch (FormatException)
                    {
                        dtAxaliGadacemisDackebisDro = DateTime.ParseExact(arrBoloStriqonisMonacemebi[5] + " " + arrBoloStriqonisMonacemebi[6]
                                                                          //, @"dd\/M\/yyyy HH:mm:ss"
                                                                          , @"dd\/M\/yyyy HH:mm:ss"
                                                                          , CultureProvider);
                    }
                    return(true);
                }
                else
                {
                    sShemdegiGadacemisSaxeli    = null;
                    dtAxaliGadacemisDackebisDro = DateTime.Now;
                    return(false);
                }
            }
            catch (WebException)
            {
                sShemdegiGadacemisSaxeli    = null;
                dtAxaliGadacemisDackebisDro = DateTime.Now;
                Console.WriteLine("CSV File not found for current day. ");
                return(false);
            }
        }
예제 #53
0
 /* List Directory Contents in Detail (Name, Size, Created, etc.) */
 public string[] directoryListDetailed(string directory)
 {
     try
     {
         /* Create an FTP Request */
         ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + directory);
         /* Log in to the FTP Server with the User Name and Password Provided */
         ftpRequest.Credentials = new NetworkCredential(user, pass);
         /* When in doubt, use these options */
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         /* Specify the Type of FTP Request */
         ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
         /* Establish Return Communication with the FTP Server */
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         /* Establish Return Communication with the FTP Server */
         ftpStream = ftpResponse.GetResponseStream();
         /* Get the FTP Server's Response Stream */
         StreamReader ftpReader = new StreamReader(ftpStream);
         /* Store the Raw Response */
         string directoryRaw = null;
         /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
         try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
         /* Resource Cleanup */
         ftpReader.Close();
         ftpStream.Close();
         ftpResponse.Close();
         ftpRequest = null;
         /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
         try { string[] directoryList = directoryRaw.Split("|".ToCharArray()); return directoryList; }
         catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     }
     catch (Exception ex) { Console.WriteLine(ex.ToString()); }
     /* Return an Empty string Array if an Exception Occurs */
     return new string[] { "" };
 }
예제 #54
0
 internal void SetCompleted(bool synch, FtpWebResponse response)
 {
     SetCompleted(synch, null, response);
 }
예제 #55
-1
        //download method
        public void DownloadFile(string remoteFile, string localFile)
        {
            try
            {
                //Creating the FTP Request, its settings, and login handling//
                //sends request
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(host + "/" + remoteFile));
                //log in to the server with the credentials
                ftpRequest.Credentials = new NetworkCredential(username, password);
                //specifies request type
                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile; 

                //toggables//
                ftpRequest.UseBinary = true; //specifies file types for transfers is binary
                ftpRequest.UsePassive = true; //specifies that the connection is from the client to the server
                ftpRequest.KeepAlive = true; //specifies we want the connetion to continue after the request is complete
                

                //Creates the communication for the server to the client and creates a io stream in which the file can be written//
                //establishes server to client communication
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                //gets the servers response stream
                ftpStream = ftpResponse.GetResponseStream(); 
                //creates a File Stream to write the downloaded file
                FileStream localFileStream = new FileStream(localFile + "\\" + remoteFile, FileMode.Create); 
                //buffer for downloading the data in bytes it is an array of bytes of the size of the remote file.
                byte[] byteBuffer = new byte[Convert.ToInt32(getFileSize(remoteFile))]; 
                //length of the bytes read in the stream
                int bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile))); //bytes are read from the stream and the number of bytes read are stored into this variable
                //the stream reads in a maximum of bytes equal to the size of the remote file. these bytes are then stored into the bytebuffer array starting at the 0 position within the array.
                //the position of the stream is then advanced by the number of bytes in which are read

                try
                {
                    while (bytesRead > 0) //loops until no bytes are being read
                    {
                        //writes the byte data into the local file
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        //reads more byte data
                        bytesRead = ftpStream.Read(byteBuffer, 0, Convert.ToInt32(getFileSize(remoteFile)));
                    }
                }
                catch (Exception ex) //error message
                {
                    MessageBox.Show(ex.Message);
                }

                //closes processes and resources
                ftpResponse.Close();
                ftpStream.Close();
                localFileStream.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }