Close() public method

Closes the underlying FTP response stream, but does not close control connection

public Close ( ) : void
return void
Exemplo n.º 1
0
        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;
            }
             
        }
Exemplo n.º 2
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);
                }
            }
        }
Exemplo n.º 3
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;
        }
Exemplo n.º 4
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);
            }
        }
Exemplo n.º 5
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;
        }
Exemplo n.º 6
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;
 }
Exemplo n.º 7
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);
            }
        }
Exemplo n.º 8
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);
                }
            }
        }
Exemplo n.º 9
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;
        }
Exemplo n.º 10
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
        }
Exemplo n.º 11
0
 /* 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;
 }
Exemplo n.º 12
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;
 }
Exemplo n.º 13
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();
        }
Exemplo n.º 14
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;
            }
        }
Exemplo n.º 15
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;
 }
Exemplo n.º 16
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);
     }
 }
Exemplo n.º 17
0
        /* 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;
        }
Exemplo n.º 18
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);
                }
            }
        }
Exemplo n.º 19
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);
            }
        }
Exemplo n.º 20
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";
            }
        }
Exemplo n.º 21
0
 /// <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();
         }
     }
 }
Exemplo n.º 22
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;
 }
Exemplo n.º 23
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;
        }
Exemplo n.º 24
0
        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);                
            }
        }
Exemplo n.º 25
0
        public void Download(string remoteFile, string localFile)
        {
            try
            {
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);

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

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

                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpStream = ftpResponse.GetResponseStream();

                FileStream localFileStream = new FileStream(localFile, FileMode.Create);

                byte[] byteBuffer = new byte[bufferSize];
                int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);

                try
                {
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }

                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            return;
        }
Exemplo n.º 26
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;
 }
Exemplo n.º 27
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;
        }
Exemplo n.º 28
0
        private long GetRemoteFileSize(string targetPath)
        {
            long size = -1;
            var ftpWebRequest = GetFtpWebRequest(targetPath);
            ftpWebRequest.Method = WebRequestMethods.Ftp.GetFileSize;

            LogStepFtpRequest(ftpWebRequest.RequestUri, string.Format("{0} {1}", ftpWebRequest.Method, targetPath));

            try
            {
                LastResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
                size = LastResponse.ContentLength;
            }
            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 size;
        }
Exemplo n.º 29
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();
            }
        }
Exemplo n.º 30
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);
            }
        }
Exemplo n.º 31
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);
                }
            }
        }
Exemplo n.º 32
0
        private bool Download(string sourcePath, string destinationPath, int offsetByte = 0)
        {
            var ftpWebRequest = GetFtpWebRequest(sourcePath);
            ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpWebRequest.ContentOffset = offsetByte;

            LogStepFtpRequest(ftpWebRequest.RequestUri, string.Format("{0} {1}, {2}", ftpWebRequest.Method, sourcePath, destinationPath));

            var result = false;
            var fileInfo = new FileInfo(destinationPath);
            using (var fileStream = fileInfo.OpenWrite())
            {
                try
                {
                    LastResponse = (FtpWebResponse) ftpWebRequest.GetResponse();
                    var responseStream = LastResponse.GetResponseStream();
                    fileStream.Seek(offsetByte, SeekOrigin.Begin);
                    result = TransferData(responseStream, fileStream);
                }
                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 result;
        }
Exemplo n.º 33
0
 public void makeDir(string newDir)
 {
     try
     {
         ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, newDir));
         ftpRequest.Credentials = new NetworkCredential(userName, password);
         ftpRequest.UseBinary = true;
         ftpRequest.UsePassive = true;
         ftpRequest.KeepAlive = true;
         ftpRequest.EnableSsl = true;
         ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
         ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
         ftpResponse.Close();
         ftpRequest = null;
     }
     catch (WebException)
     {
         Console.WriteLine("Error in making directory. Directory may already exist.");
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error in makeDir.\n" + ex.ToString());
         if (ftpResponse != null)
             ftpResponse.Close();
         if (ftpRequest != null)
             ftpRequest = null;
     }
 }
Exemplo n.º 34
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;
        }
Exemplo n.º 35
0
        public void rename(string oldNameAndPath, string newFileName)
        {
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, oldNameAndPath));

                ftpRequest.Credentials = new NetworkCredential(userName, password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.EnableSsl = true;

                ftpRequest.Method = WebRequestMethods.Ftp.Rename;

                ftpRequest.RenameTo = newFileName;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                if (ftpResponse != null)
                    ftpResponse.Close();
                if (ftpRequest != null)
                    ftpRequest = null;

                Console.WriteLine("An error occurred in Rename\n" + ex.ToString());
            }
            return;
        }
Exemplo n.º 36
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;
        }
Exemplo n.º 37
0
        private string[] lsSimple(string dir)
        {
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(String.Format(baseUrl, dir));
                ftpRequest.Credentials = new NetworkCredential(userName, password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.EnableSsl = true;

                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                ftpStream = ftpResponse.GetResponseStream();

                StreamReader ftpReader = new StreamReader(ftpStream);

                StringBuilder result = new StringBuilder();
                try
                {
                    string line = ftpReader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("\n");
                        line = ftpReader.ReadLine();
                    }
                    //remove extra \n
                    result.Remove(result.ToString().LastIndexOf('\n'), 1);
                    ftpReader.Close();
                    ftpStream.Close();
                    ftpResponse.Close();
                    ftpRequest = null;
                    return result.ToString().Split('\n');
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error reading file list.\n" + ex.ToString());
                    if (result != null)
                        result = null;
                    if (ftpReader != null)
                        ftpReader.Close();
                    if (ftpResponse != null)
                        ftpResponse.Close();
                    if (ftpRequest != null)
                        ftpRequest = null;
                    return new string[] { "" };
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return new string[] { "" };
        }
Exemplo n.º 38
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");
     }
 }
        // Anslutning till FTP - Server och listar innehållet
        public bool LoginCheck()
        {
            try
            {
                // Skapa en FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host+":"+port);
                // Loggar in på FTP Server med användarnman och lösenord
                ftpRequest.Credentials = new NetworkCredential(user, pass);

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

                //Specificerar vilken typ av FTP Request
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                //Etablera Return kommunikation med FTP-servern
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

                // Lagra FTP Serverns svarström
                ftpStream = ftpResponse.GetResponseStream();

                // Lagra FTP Serverns svarström
                StreamReader ftpReader = new StreamReader(ftpStream);

                // Lagrar responesen i variabeln directoryRaw
                string directoryRaw = null;

                // Läser rad för ar av svaret och lägger till en | för varje rad
                try { while (ftpReader.Peek() != -1) { directoryRaw += ftpReader.ReadLine() + "|"; } }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }

                // Städar anslutningarna
                ftpReader.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;

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

                    Console.WriteLine("");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("========================================");
                    Console.ResetColor();
                    Console.WriteLine("Content of the FTP-Server");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("========================================");
                    Console.ResetColor();

                    foreach (var direct in directoryList)
                    {
                        Console.WriteLine(direct);
                    }
                    Console.WriteLine("");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("========================================");
                    Console.ResetColor();
                }
                catch (Exception ex) { Console.WriteLine(ex.ToString()); }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
Exemplo n.º 40
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 "";
 }
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            /* Create an FTP Request */
            ftpRequest = (FtpWebRequest)FtpWebRequest.Create(data.adress + "/" + remoteFile);
            /* 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.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 */
            Directory.CreateDirectory(Path.GetDirectoryName(localFile));
            localFileStream = new FileStream(localFile, FileMode.Create);
            /* Buffer for the Downloaded Data */
            byte[] byteBuffer = new byte[bufferSize];
            int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
            int totalBytesRead = bytesRead;
            /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
            while (bytesRead > 0)
            {
                if (cancel)
                {
                    localFileStream.Close();
                    ftpRequest.Abort();
                    ftpStream.Close();
                    ftpResponse.Close();
                    ftpRequest = null;
                    ftpResponse = null;
                    ftpStream = null;
                    localFileStream = null;
                    e.Cancel = true;
                    return;
                }
                localFileStream.Write(byteBuffer, 0, bytesRead);
                bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
                totalBytesRead += bytesRead;
                double progress = totalBytesRead * 100.0 / fileSize;
                WorkerState state = new WorkerState(fileSize, totalBytesRead);
                worker.ReportProgress((int)progress, state);
            }

            /* Resource Cleanup */
            localFileStream.Close();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
Exemplo n.º 42
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[] { "" };
 }
Exemplo n.º 43
-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);
            }
        }