コード例 #1
1
    /* Download File */
    public string download(string remoteFile, string localFile)
    {
        string _result = null;

        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()); }
            _localFileStream.Close();
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString());
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
コード例 #2
1
	/* 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[] { "" };
	}
コード例 #3
1
    /* List Directory Contents File/Folder Name Only */
    public List<string> directoryListSimple(string directory)
    {
        List<string> _directoryList = null;
        string _chr = "|";

        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.ListDirectory;
            /* 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 */
            while (_ftpReader.Peek() != -1)
            {
                _directoryRaw += _ftpReader.ReadLine() + _chr;
            }
            _ftpReader.Close();
            /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
            _directoryList = _directoryRaw.Split(_chr.ToCharArray()).ToList(); 
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString()); 
            _directoryList.Add(ex.Message.ToString()); 
        }
        finally
        {
            /* Resource Cleanup */
            ftpStream.Flush();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        /* Return an Empty string Array if an Exception Occurs */
        return _directoryList;
    }
コード例 #4
0
 private void DeleteFile(string destinationFile)
 {
     OnProgress("Deleting file: " + destinationFile + ".", _currentFile, _totalFiles);
     FtpWebRequest  request  = SetupFtpWebRequest(destinationFile, WebRequestMethods.Ftp.DeleteFile);
     FtpWebResponse response = (FtpWebResponse)request.GetResponse();
 }
コード例 #5
0
    /* Get the Size of a File */
    public string getFileSize(string fileName)
    {
        string _result = null;
        string _fileInfo = null;

        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 */

            /* Read the Full Response Stream */
            while (_ftpReader.Peek() != -1)
            {
                _fileInfo = _ftpReader.ReadToEnd();
            }
            _ftpReader.Close();

            /* Return File Size */
            _result = _fileInfo;
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString()); 
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            
            ftpStream.Flush();
            ftpStream.Close();
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
コード例 #6
0
ファイル: FtpManager.cs プロジェクト: 88886/jnmmes
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="localDir">下载至本地路径</param>
        /// <param name="FtpDir">ftp目标文件路径</param>
        /// <param name="FtpFile">从ftp要下载的文件名</param>
        /// <param name="hostname">ftp地址即IP</param>
        /// <param name="username">ftp用户名</param>
        /// <param name="password">ftp密码</param>
        public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
        {
            string URI       = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
            string tmpname   = Guid.NewGuid().ToString();
            string localfile = localDir + @"\" + tmpname;

            System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
            ftp.Method     = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary  = true;
            ftp.UsePassive = false;

            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int    read   = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            File.Delete(localfile);
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }



            try
            {
                File.Delete(localDir + @"\" + FtpFile);
                File.Move(localfile, localDir + @"\" + FtpFile);


                ftp        = null;
                ftp        = GetRequest(URI, username, password);
                ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
                ftp.GetResponse();
            }
            catch (Exception ex)
            {
                File.Delete(localfile);
                throw ex;
            }

            // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
            ftp = null;
        }
コード例 #7
0
        public static string[] ListingByFTP(string password, string userName, string destinationFile)
        {
            string[] val;
            string[] files;
            string   result;

            try
            {
                System.Uri    serverUri = new System.Uri(destinationFile);
                FtpWebRequest request   = (FtpWebRequest)WebRequest.Create(serverUri);
                request.Method              = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary           = true;
                request.UsePassive          = true;
                request.KeepAlive           = false;
                request.Timeout             = System.Threading.Timeout.Infinite;
                request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
                request.Credentials         = new NetworkCredential(userName, password);
                FtpWebResponse response       = (FtpWebResponse)request.GetResponse();
                Stream         responseStream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    const string SeparatorWord = "\r\n";
                    result = reader.ReadToEnd();
                    //result = result.Remove (0, 11);
                    val = result.Split(SeparatorWord);
                    if (val.Length > 3)
                    {
                        files = new string[val.Length - 3];
                    }
                    else
                    {
                        files = new string[1];
                    }
                    int i = 0;
                    files[0] = "";
                    foreach (string word in val)
                    {
                        if (!((word == "") || (word == ".") || (word == "..")))
                        {
                            files.SetValue(word, i);
                            i = i + 1;
                        }
                    }
                    response.Close();
                    response.Dispose();
                    return(files);
                }
            }
            catch (Exception e)
            {
                val = new string[1];
                if (e.Message == "The remote server returned an error: (500) 500 NLST: Connection timed out\r\n.")
                {
                    val[0] = e.Message;
                }
                else
                {
                    val[0] = "Other error";
                }

                return(val);
            }
        }
コード例 #8
0
ファイル: Form1.cs プロジェクト: OleTheDev/Server-Launcher
        public async void SyncFilesAsync(string FTPHost, string FTPUser, string FTPPW, string DownloadURL)
        {
            try
            {
                this.Invoke((MethodInvoker)(() =>
                {
                    text_Sync.Text = "Syncing...";
                }));

                FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create("ftp://" + FTPHost);
                listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                NetworkCredential credentials = new NetworkCredential(FTPUser, FTPPW);
                listRequest.Credentials = credentials;

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

                using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
                    using (Stream listStream = listResponse.GetResponseStream())
                        using (StreamReader listReader = new StreamReader(listStream))
                        {
                            while (!listReader.EndOfStream)
                            {
                                lines.Add(listReader.ReadLine());
                            }

                            listReader.Close();
                        }

                Globals.FTPFilesFound.Clear();
                Globals.FTPFiles           = 0;
                Globals.FTPFilesDownloaded = 0;

                foreach (string line in lines)
                {
                    string[] tokens      = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
                    string   name        = tokens[8];
                    string   permissions = tokens[0];

                    Globals.FTPFilesFound.Add(name);
                    Globals.FTPFiles++;
                }

                this.Invoke((MethodInvoker)(() =>
                {
                    progressBar1.Minimum = 0;
                    progressBar1.Value = 0;
                    progressBar1.Maximum = Globals.FTPFiles;
                }));

                if (!(Directory.Exists(Globals.a3Path + "\\@ArmaCore\\addons\\")))
                {
                    Directory.CreateDirectory(Globals.a3Path + "\\@ArmaCore\\addons\\");
                }

                CurrentFiles = Directory.GetFiles(@"" + Globals.a3Path + "\\@ArmaCore\\addons\\", "*");
                string path = Globals.a3Path;

                bool FileFound;

                foreach (string file in CurrentFiles)
                {
                    FileFound = false;

                    string filenew = Path.GetFileName(file);

                    foreach (string filename in Globals.FTPFilesFound)
                    {
                        if (filenew == filename)
                        {
                            FileFound = true;
                        }
                    }

                    if (FileFound == false)
                    {
                        File.Delete(file);
                        Globals.FTPFilesFound.Remove(file);
                        Globals.FTPFiles = Globals.FTPFiles - 1;
                    }
                }

                if (Globals.FTPFiles <= 0)
                {
                    this.Invoke((MethodInvoker)(() =>
                    {
                        progressBar1.Value = 0;
                    }));
                }

                this.Invoke((MethodInvoker)(() =>
                {
                    progressBar1.Maximum = Globals.FTPFiles;
                }));

                bool canceled = false;

                Globals.CancelDownload          = false;
                Globals.FileDownload_InProgress = false;

                foreach (string file in Globals.FTPFilesFound)
                {
                    if (Globals.CancelDownload == true)
                    {
                        Globals.CancelDownload = false;
                        canceled = true;
                        break;
                    }

                    Globals.FileDownload_InProgress = true;

                    this.Invoke((MethodInvoker)(() =>
                    {
                        text_Sync.Text = "Syncing file " + file + "...";
                    }));

                    string fileTypeurl = @"" + DownloadURL + file;
                    string fileType    = System.IO.Path.GetExtension(fileTypeurl);

                    if (fileType == ".pbo" || fileType == ".ebo" || fileType == ".bisign")
                    {
                        DownloadFile(DownloadURL + file, @"" + path + "\\@ArmaCore\\addons\\" + file, file, path);
                    }
                    else
                    {
                        DownloadFile(DownloadURL + file, @"" + path + "\\@ArmaCore\\" + file, file, path);
                    }


                    await Task.Delay(50);

                    while (Globals.FileDownload_InProgress == true)
                    {
                        await Task.Delay(50);

                        if (Globals.CancelDownload == true)
                        {
                            break;
                        }
                    }
                }


                if (canceled == false)
                {
                    MessageBox.Show("Download finished!", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Invoke((MethodInvoker)(() =>
                    {
                        text_Sync.Text = "";
                        text_fileDownloading.Text = "Downloading File:";
                        text_speed.Text = "Download Speed:";
                        labelPerc.Text = "File Download Percentage:";
                        labelDownloaded.Text = "Downloaded:";

                        progressBar1.Value = 0;
                        progressBar2.Value = 0;

                        button4.Enabled = false;
                        button5.Enabled = true;
                        button3.Enabled = true;
                    }));
                }
                else
                {
                    MessageBox.Show("Download canceled!", "Canceled", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Invoke((MethodInvoker)(() =>
                    {
                        text_Sync.Text = "";
                        text_fileDownloading.Text = "Downloading File:";
                        text_speed.Text = "Download Speed:";
                        labelPerc.Text = "File Download Percentage:";
                        labelDownloaded.Text = "Downloaded:";

                        progressBar1.Value = 0;
                        progressBar2.Value = 0;

                        button4.Enabled = false;
                        button5.Enabled = true;
                        button3.Enabled = true;
                    }));
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(er.ToString(), "Error with syncing", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #9
0
        public string descargarArchivo(string nombreArchivo, string nombreCarpeta)
        {
            try
            {
                resultadoAuditoria = operadorSQL.registrarAuditoria(nombreArchivo, nombreCarpeta + "/" + nombreArchivo, "Descargando el archivo del FTP", estadoDescargando, true, false, false);
                idProceso          = int.Parse(resultadoAuditoria.Substring(resultadoAuditoria.IndexOf("[") + 1, 1));

                solicitudFTP             = (FtpWebRequest)WebRequest.Create(servidorFTP + nombreCarpeta + "/" + nombreArchivo);
                solicitudFTP.UseBinary   = true;
                solicitudFTP.Method      = WebRequestMethods.Ftp.DownloadFile;
                solicitudFTP.Credentials = credencialesFTP;
                solicitudFTP.KeepAlive   = false;
                solicitudFTP.UsePassive  = false;

                Console.WriteLine("Inicia descarga de archivo por FTP " + nombreArchivo);
                resupuestaFTP = (FtpWebResponse)solicitudFTP.GetResponse();
                Console.WriteLine("Finaliza descarga de archivo por FTP " + nombreArchivo);

                streamResultados    = resupuestaFTP.GetResponseStream();
                rutaLocalAlmacenaje = Path.Combine(rutaRaizNatura + nombreCarpeta, nombreArchivo.Replace(extencionArchivosFTP, extencionArchivosLocales));

                if (File.Exists(rutaLocalAlmacenaje))
                {
                    File.Delete(rutaLocalAlmacenaje);
                    streamArchivo = File.Create(rutaLocalAlmacenaje);
                    int lectorArchivo;
                    bufferArchivo = new byte[1024];
                    while ((lectorArchivo = streamResultados.Read(bufferArchivo, 0, bufferArchivo.Length)) > 0)
                    {
                        streamArchivo.Write(bufferArchivo, 0, lectorArchivo);
                    }
                    streamArchivo.Close();
                }
                else
                {
                    streamArchivo = File.Create(rutaLocalAlmacenaje);
                    int lectorArchivo;
                    bufferArchivo = new byte[1024];
                    while ((lectorArchivo = streamResultados.Read(bufferArchivo, 0, bufferArchivo.Length)) > 0)
                    {
                        streamArchivo.Write(bufferArchivo, 0, lectorArchivo);
                    }
                    streamArchivo.Close();
                }

                if (Path.GetExtension(nombreArchivo).Equals(extencionArchivosFTP))
                {
                    operadorSQL.actualizarAuditoria(idProceso, nombreArchivo, nombreCarpeta + "/" + nombreArchivo, "Cambiando Codificación del Archivo a UNICODE", estadoCambiandoCod, true, true, false);
                    File.WriteAllText(rutaLocalAlmacenaje, File.ReadAllText(rutaLocalAlmacenaje, Encoding.UTF8), Encoding.BigEndianUnicode);
                }
                else
                {
                    operadorSQL.actualizarAuditoria(idProceso, nombreArchivo, nombreCarpeta + "/" + nombreArchivo, "NO SE REALIZA el Cambio de Codificación del Archivo a UNICODE, ya que no es un archivo CSV", estadoCambiandoCod, true, true, false);
                }

                File.Move(rutaLocalAlmacenaje, rutaLocalAlmacenaje.Replace(extencionArchivosLocales, extencionArchivosFTP));
                resultadoProceso = "Archivo descargado Exitosamente en la ruta: " + rutaRaizNatura + nombreCarpeta + "\\" + nombreArchivo;
                Console.WriteLine(resultadoProceso);
            }
            catch (Exception ex)
            {
                resultadoProceso = "Error Descargando Archivos en Local desde FTP o el el proceso de Codificacion o Modificacion de Archivos  - " + ex;
                Console.WriteLine(resultadoProceso);
                logProcesos.registrarLog("OperadorArchivos", resultadoProceso, 0);
                operadorSQL.actualizarAuditoria(idProceso, nombreArchivo, nombreCarpeta + "/" + nombreArchivo, resultadoProceso, estadoFallido, true, true, false);
            }
            finally
            {
                if (lectorStramsResultados != null)
                {
                    lectorStramsResultados.Close();
                }
                if (streamResultados != null)
                {
                    streamResultados.Close();
                }
            }

            return(resultadoProceso);
        }
コード例 #10
0
ファイル: MSKB-FtpWebRequest.cs プロジェクト: dglaser/Agent
    private WebResponse GetFtpResponse()
    {
        FtpWebResponse ftpresponse = null;

        if(m_CommandType == FtpCommandType.FtpDataReceiveCommand
          || m_CommandType == FtpCommandType.FtpDataSendCommand)
        {
          if(_bPassiveMode)
          {
        OpenPassiveDataConnection();
          }
          else
        OpenDataConnection();
        }

        //
        // negotiate data connection
        //
        string sztype = "I";
        if(m_szContentType == "ascii")
        {
          sztype = "A";
        }

        SendCommand("TYPE",sztype);

        ResponseDescription resp_desc = ReceiveCommandResponse();

        if(!resp_desc.PositiveCompletion)
        {
          throw new ApplicationException("Data negotiation failed:\n" + m_sbControlSocketLog.ToString());
        }

        if(m_szServerMethod == "PWD")
          m_szCmdParameter = null;

        SendCommand(m_szServerMethod, m_szCmdParameter);

        //ftpresponse = ReceiveResponse();
        resp_desc = ReceiveCommandResponse();

        if(m_CommandType == FtpCommandType.FtpDataSendCommand)
        {
          //if(resp_desc.Status/100 == 1) // Positive preliminary reply
          if(resp_desc.PositivePreliminary) // Positive preliminary reply
          {
        if(m_RequestStream != null)
        {
          Socket DataConnection;
          if( _bPassiveMode)
            DataConnection = m_DataSocket;
          else
            DataConnection = m_DataSocket.Accept();
          if(DataConnection == null)
          {
            throw new ProtocolViolationException("Accept failed ");
          }

          SendData(DataConnection);
          DataConnection.Close();

          //ftpresponse = ReceiveResponse();
          ResponseDescription resp = ReceiveCommandResponse();

          ftpresponse = new FtpWebResponse(resp.Status, resp.StatusDescription, m_sbControlSocketLog.ToString());
        }
        else
        {  // Data to be send is not specified
          throw new ApplicationException("Data to be uploaded not specified");
        }
          }
          else
          {
        //Console.WriteLine(resp_desc.StatusDescription);
        m_Exception = new ApplicationException(ComposeExceptionMessage(resp_desc, m_sbControlSocketLog.ToString()));
          }
          CloseDataConnection();
        }
        else if(m_CommandType == FtpCommandType.FtpDataReceiveCommand)
        {
          //if(resp_desc.Status/100 == 1) // Positive preliminary reply
          if(resp_desc.PositivePreliminary) // Positive preliminary reply
          {
        Socket DataConnection;
        if( _bPassiveMode)
          DataConnection = m_DataSocket;
        else
          DataConnection = m_DataSocket.Accept();
        if(DataConnection == null)
        {
          throw new ProtocolViolationException("DataConnection failed ");
        }
        Stream datastream = ReceiveData(DataConnection);
        //ftpresponse = ReceiveResponse();
        ResponseDescription resp = ReceiveCommandResponse();
        ftpresponse = new FtpWebResponse(resp.Status, resp.StatusDescription, m_sbControlSocketLog.ToString());
        ftpresponse.SetDownloadStream(datastream);
          }
          else
          {
        m_Exception = new ApplicationException(ComposeExceptionMessage(resp_desc, m_sbControlSocketLog.ToString()));
          }

          CloseDataConnection();
        }
        else
        {
          //
          // htis is a FtpControlCommand
          //
          ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
        }

        if(m_Exception != null)
        {
          Debug.Assert(ftpresponse == null);
          throw m_Exception;
        }

        return ftpresponse;
    }
コード例 #11
0
        public static string DownloadAddonPackage(string _FTPDownloadAddress, int _AddonPackageFileSize, Action <float> _DownloadProgress = null)
        {
            try
            {
                int fileNameStartIndex = _FTPDownloadAddress.LastIndexOf('\\');
                if (fileNameStartIndex == -1 || fileNameStartIndex < _FTPDownloadAddress.LastIndexOf('/'))
                {
                    fileNameStartIndex = _FTPDownloadAddress.LastIndexOf('/');
                }
                string fileName = StaticValues.LauncherDownloadsDirectory + _FTPDownloadAddress.Substring(fileNameStartIndex + 1);

                FtpWebRequest    ftpRequest  = null;
                FtpWebResponse   ftpResponse = null;
                System.IO.Stream ftpStream   = null;
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)FtpWebRequest.Create(_FTPDownloadAddress);
                _DownloadProgress(0.1f);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential("WowLauncherUpdater", "");
                /* 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();
                _DownloadProgress(0.2f);
                /* Get the FTP Server's Response Stream */
                ftpStream = ftpResponse.GetResponseStream();
                /* Open a File Stream to Write the Downloaded File */
                Utility.AssertFilePath(fileName);
                System.IO.FileStream localFileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Create);
                _DownloadProgress(0.3f);
                /* Buffer for the Downloaded Data */
                byte[] byteBuffer = new byte[2048];
                int    bytesRead  = ftpStream.Read(byteBuffer, 0, 2048);
                /* Download the File by Writing the Buffered Data Until the Transfer is Complete */
                int totalDownloaded = 0;
                try
                {
                    while (bytesRead > 0)
                    {
                        localFileStream.Write(byteBuffer, 0, bytesRead);
                        totalDownloaded += bytesRead;
                        if (_AddonPackageFileSize != 0)
                        {
                            float progressValue = 0.3f + ((float)totalDownloaded / (float)_AddonPackageFileSize) * 0.65f;
                            if (progressValue <= 0.95f)
                            {
                                _DownloadProgress(progressValue);
                            }
                        }
                        bytesRead = ftpStream.Read(byteBuffer, 0, 2048);
                    }
                }
                catch (Exception ex) { Logger.LogException(ex); }
                /* Resource Cleanup */
                localFileStream.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;
                _DownloadProgress(1.0f);
                return(fileName);
            }
            catch (Exception ex) { Logger.LogException(ex); }
            return("");
        }
コード例 #12
0
        //Version taking string/FileInfo
        public bool Download(string sourceFilename, FileInfo targetFI, bool PermitOverwrite)
        {
            //1. check target
            if (targetFI.Exists && !(PermitOverwrite))
            {
                throw (new ApplicationException("Target file already exists"));
            }

            //2. check source
            string target;

            if (sourceFilename.Trim() == "")
            {
                throw (new ApplicationException("File not specified"));
            }
            else if (sourceFilename.Contains("/"))
            {
                //treat as a full path
                target = AdjustDir(sourceFilename);
            }
            else
            {
                //treat as filename only, use current directory
                target = CurrentDirectory + sourceFilename;
            }

            string URI = Hostname + target;

            //3. perform copy
            System.Net.FtpWebRequest ftp = GetRequest(URI);

            //Set request to download a file in binary mode
            ftp.Method    = System.Net.WebRequestMethods.Ftp.DownloadFile;
            ftp.UseBinary = true;

            //open request and get response stream
            using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    //loop to read & write to file
                    using (FileStream fs = targetFI.OpenWrite())
                    {
                        try
                        {
                            byte[] buffer = new byte[2048];
                            int    read   = 0;
                            do
                            {
                                read = responseStream.Read(buffer, 0, buffer.Length);
                                fs.Write(buffer, 0, read);
                            } while (!(read == 0));
                            responseStream.Close();
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            //catch error and delete file only partially downloaded
                            fs.Close();
                            //delete target file as it's incomplete
                            targetFI.Delete();
                            throw;
                        }
                    }

                    responseStream.Close();
                }

                response.Close();
            }


            return(true);
        }
コード例 #13
0
ファイル: Utils.cs プロジェクト: maumaya8110/SICAS_WF_SAT
        public static void FTPDownload(string ftpSource, string localDest, string ftpUserID, string ftpPassword)
        {
            FTP_ISBUSY = true;
            try
            {
                FtpWebRequest reqFTP;
                FileStream    outputStream = new FileStream(localDest, FileMode.Create);

                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpSource));
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID,
                                                           ftpPassword);
                reqFTP.UsePassive = false;

                reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                FTP_FILESIZE = response.ContentLength;

                //  Volver a crear
                reqFTP             = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpSource));
                reqFTP.UseBinary   = true;
                reqFTP.Credentials = new NetworkCredential(ftpUserID,
                                                           ftpPassword);
                reqFTP.UsePassive = false;

                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                response      = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                int    bufferSize = 2048;
                int    readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);

                long cont = readCount;

                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);

                    FTP_PERCENT = Convert.ToInt32((cont * 100) / Math.Abs(FTP_FILESIZE));
                    cont       += readCount;

                    if (FTP_PERCENT > 0)
                    {
                        Console.WriteLine(String.Format("{0} * 100 / {1} = {2}", cont, FTP_FILESIZE, FTP_PERCENT));
                        pb.Value = FTP_PERCENT;
                    }
                    else
                    {
                        Console.WriteLine("MENOR QUE 0");
                    }
                }

                ftpStream.Close();
                outputStream.Close();
                response.Close();
            }
            finally
            {
                FTP_ISBUSY   = false;
                FTP_FILESIZE = 0;
                FTP_PERCENT  = 0;
            }
        }
コード例 #14
0
        private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            FtpSettings      f  = e.Argument as FtpSettings;
            // set up the host string to request.  this includes the target folder and the target file name (based on the source filename)
            string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(f.SourceFile));

            if (!UploadPath.ToLower().StartsWith("ftp://"))
            {
                UploadPath = "ftp://" + UploadPath;
            }
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);

            request.UseBinary   = true;
            request.UsePassive  = f.Passive;
            request.Method      = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(f.Username, f.Password);

            // Copy the contents of the file to the request stream.
            long   FileSize = new FileInfo(f.SourceFile).Length;
            string FileSizeDescription = GetFileSize(FileSize);             // e.g. "2.4 Gb" instead of 240000000000000 bytes etc...
            int    ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
            long   SentBytes = 0;

            byte[] Buffer = new byte[ChunkSize];                // this buffer stores each chunk, for sending to the web service via MTOM
            using (Stream requestStream = request.GetRequestStream())
            {
                using (FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    int BytesRead = fs.Read(Buffer, 0, ChunkSize);                      // read the first chunk in the buffer
                    // send the chunks to the web service one by one, until FileStream.Read() returns 0, meaning the entire file has been read.
                    while (BytesRead > 0)
                    {
                        try
                        {
                            if (bw.CancellationPending)
                            {
                                return;
                            }

                            // send this chunk to the server.  it is sent as a byte[] parameter, but the client and server have been configured to encode byte[] using MTOM.
                            requestStream.Write(Buffer, 0, BytesRead);

                            // sentBytes is only updated AFTER a successful send of the bytes. so it would be possible to build in 'retry' code, to resume the upload from the current SentBytes position if AppendChunk fails.
                            SentBytes += BytesRead;

                            // update the user interface
                            string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
                            bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine("Exception: " + ex.ToString());
                            if (NumRetries++ < MaxRetries)
                            {
                                // rewind the filestream and keep trying
                                fs.Position -= BytesRead;
                            }
                            else
                            {
                                throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
                            }
                        }
                        BytesRead = fs.Read(Buffer, 0, ChunkSize);                              // read the next chunk (if it exists) into the buffer.  the while loop will terminate if there is nothing left to read
                    }
                }
            }
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
        }
コード例 #15
0
        public bool DownloadFile(string filename, long UpdateLen, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;

            try   {
                string savePath = System.AppDomain.CurrentDomain.BaseDirectory;
                //int ret = FtpHelper.DownloadFtp(savePath, "Update.zip", "183.60.106.146", "FtpUser", "*****@*****.**");
                FtpWebResponse response   = FtpHelper.GetFtpWebResponse(filename, "183.60.106.146", "FtpUser", "*****@*****.**");
                Stream         ftpStream  = response.GetResponseStream();
                long           totalBytes = UpdateLen;

                this.Invoke((EventHandler) delegate { this.progressBar1.Value = 0; });
                this.Invoke((EventHandler) delegate
                {
                    if (prog != null)
                    {
                        prog.Maximum = (int)UpdateLen;
                    }
                });

                long       totalDownloadedByte = 0;
                FileStream outputStream        = new FileStream(savePath + filename, FileMode.Create);

                int    bufferSize = 2048;
                int    readCount;
                byte[] buffer = new byte[bufferSize];

                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    totalDownloadedByte = readCount + totalDownloadedByte;
                    this.Invoke((EventHandler) delegate
                    {
                        if (prog != null)
                        {
                            prog.Value = (int)totalDownloadedByte;
                        }
                    });
                    System.Windows.Forms.Application.DoEvents();

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    this.Invoke((EventHandler) delegate
                    {
                        label1.Text = "当前补丁下载进度" + percent.ToString() + "%";
                    });


                    System.Windows.Forms.Application.DoEvents();

                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                outputStream.Close();
                ftpStream.Close();
                response.Close();
                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(System.AppDomain.CurrentDomain.BaseDirectory, ex.Message, new StackTrace(new StackFrame(true)));

                return(false);
            }
        }
コード例 #16
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                String   RemoteFtpPath = txtlink.Text;
                string[] Arr           = RemoteFtpPath.Split(':');

                if (Arr[0] == "http" || Arr[0] == "https")
                {
                    if (rbtHTTP.Checked == true)
                    {
                        wc.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloadCompleted);
                        Uri imageUrl = new Uri(RemoteFtpPath);
                        wc.DownloadFileAsync(imageUrl, "test.gif");
                    }
                    else
                    {
                        MessageBox.Show("http link is not allowed.");
                    }
                }
                else if (Arr[0] == "ftp")
                {
                    if (rbtFTP.Checked == true)
                    {
                        String  LocalDestinationPath = "D:\\test.png";
                        String  Username             = txtname.Text;
                        String  Password             = txtpass.Text;
                        Boolean UseBinary            = true; // use true for .zip file or false for a text file
                        Boolean UsePassive           = false;

                        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(RemoteFtpPath);
                        request.Method     = WebRequestMethods.Ftp.DownloadFile;
                        request.KeepAlive  = true;
                        request.UsePassive = UsePassive;
                        request.UseBinary  = UseBinary;

                        request.Credentials = new NetworkCredential(Username, Password);

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

                        Stream       responseStream = response.GetResponseStream();
                        StreamReader reader         = new StreamReader(responseStream);

                        using (FileStream writer = new FileStream(LocalDestinationPath, FileMode.Create))
                        {
                            long   length     = response.ContentLength;
                            int    bufferSize = 2048;
                            int    readCount;
                            byte[] buffer = new byte[2048];

                            readCount = responseStream.Read(buffer, 0, bufferSize);
                            while (readCount > 0)
                            {
                                writer.Write(buffer, 0, readCount);
                                readCount = responseStream.Read(buffer, 0, bufferSize);
                            }
                        }
                        reader.Close();
                        response.Close();
                        MessageBox.Show("File downloaded completed.");
                    }
                    else
                    {
                        MessageBox.Show("ftp link is not allowed.");
                    }
                }
            }
            catch (Exception ex) { }
        }
コード例 #17
0
        public List <KeyValuePair <string, string> > GetALLFilesFromFTP(string ClaimId, FtpCredentials ftpCredentials)
        {
            List <string> Entries = new List <string>();
            List <KeyValuePair <string, string> > FileName = new List <KeyValuePair <string, string> >();

            try
            {
                List <ClaimUploadStatus> FolderNames = Enum.GetValues(typeof(ClaimUploadStatus)).Cast <ClaimUploadStatus>().ToList();

                NetworkCredential networkcredentials = new NetworkCredential(ftpCredentials.FTPUserName, ftpCredentials.FTPPassword);

                foreach (ClaimUploadStatus foldername in FolderNames)
                {
                    //Create FTP Request.
                    string folderpath = string.Format("{0}/{1}", ftpCredentials.FTPAddress, ClaimId);

                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderpath);
                    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                    //Enter FTP Server credentials.
                    request.Credentials = networkcredentials;
                    request.UsePassive  = true;
                    request.UseBinary   = true;
                    request.EnableSsl   = false;
                    request.KeepAlive   = true;

                    //Fetch the Response and read it using StreamReader.
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        //Read the Response as String and split using New Line character.
                        Entries = reader.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    }

                    response.Close();

                    //Loop and add details of each File to the DataTable.
                    foreach (string entry in Entries)
                    {
                        string[] splits = entry.Split(new string[] { " ", }, StringSplitOptions.RemoveEmptyEntries);

                        //Determine whether entry is for File or Directory
                        bool isFile = splits[0].Substring(0, 1) != "d";

                        if (isFile)
                        {
                            if (splits.Count() >= 8)
                            {
                                FileName.Add(new KeyValuePair <string, string>(foldername.ToString(), splits[8]));
                            }
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                LoggerService.LogExceptionsToDebugConsole(ex);
                throw ex;
            }

            return(FileName);
        }
コード例 #18
0
		/// <summary>
		/// Sends the request to the server and returns the response
		/// </summary>
		/// <returns>Returns an FtpWebResponse which can be used to access the response from the request</returns>
		public override WebResponse GetResponse()
		{
			OpenDataConnection();
			ftpWebResponse = new FtpWebResponse( dataStream );
			return ftpWebResponse;
		}
コード例 #19
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 "";
	}
コード例 #20
0
        /// <summary>
        /// 从服务器获取指定路径下文件及子目录列表,并显示
        /// </summary>
        /// <returns>操作是否成功</returns>
        private bool ShowFtpFileAndDirectory()
        {
            listBoxFtp.Items.Clear();
            string uri = string.Empty;

            if (currentDir == "/")
            {
                uri = ftpUriString;
            }
            else
            {
                uri = ftpUriString + currentDir;
            }
            FtpWebRequest request = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.ListDirectoryDetails);
            //获取服务器端响应
            FtpWebResponse response = GetFtpResponse(request);

            if (response == null)
            {
                return(false);
            }
            listBoxInfo.Items.Add("服务器返回:" + response.StatusDescription);
            //读取网络流信息
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string       s  = sr.ReadToEnd();

            string[] ftpDir = s.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            //在listBoxInfo中显示服务器响应的原信息
            listBoxInfo.Items.AddRange(ftpDir);
            listBoxInfo.Items.Add("服务器返回:" + response.StatusDescription);
            //添加单击能返回上层目录的项
            listBoxFtp.Items.Add("返回上层目录");
            int len = 0;

            for (int i = 0; i < ftpDir.Length; i++)
            {
                if (ftpDir[i].EndsWith("."))
                {
                    len = ftpDir[i].Length - 2;
                    break;
                }
            }
            for (int i = 0; i < ftpDir.Length; i++)
            {
                s = ftpDir[i];
                int index = s.LastIndexOf('\t');
                if (index == -1)
                {
                    if (len < s.Length)
                    {
                        index = len;
                    }
                    else
                    {
                        continue;
                    }
                }
                string name = s.Substring(index + 1);
                if (name == "." || name == "..")
                {
                    continue;
                }
                //判断是否为目录,在项前进行表示
                if (s[0] == 'd' || (s.ToLower()).Contains("<dir>"))
                {
                    listBoxFtp.Items.Add("[目录]" + name);
                }
            }
            for (int i = 0; i < ftpDir.Length; i++)
            {
                s = ftpDir[i];
                int index = s.LastIndexOf('\t');
                if (index == -1)
                {
                    if (len < s.Length)
                    {
                        index = len;
                    }
                    else
                    {
                        continue;
                    }
                }
                string name = s.Substring(index + 1);
                if (name == "." || name == "..")
                {
                    continue;
                }
                //判断是否为文件,在项前进行表示
                if (!(s[0] == 'd' || (s.ToLower()).Contains("<dir>")))
                {
                    listBoxFtp.Items.Add("[文件]" + name);
                }
            }
            return(true);
        }
コード例 #21
0
        public static void Upload(FileInfo file, string pathName)
        {
            string rootPath = @"ftp://" + AppConfig.FTPServerIP + "/dev/neomp-data/";//根目录

            CheckDirectoryAndMake(rootPath, pathName);

            //文件上传地址根目录,这里通过IIS架设本地主机为FTP服务器
            string FileSaveUri = rootPath + pathName;

            Stream         requestStream  = null;
            Stream         fileStream     = null;
            FtpWebResponse uploadResponse = null; //创建FtpWebResponse实例uploadResponse
                                                  //Btn_Upload.

            //获取文件长度
            int FileLength = Convert.ToInt32(file.Length);

            //限制上传文件最大不能超过1G
            if (FileLength < 1024 * 1024 * 1024)
            {
                try
                {
                    //格式化为URI
                    Uri           uri           = new Uri(FileSaveUri + "/" + Path.GetFileName(file.Name));
                    FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);                                       //创建FtpWebRequest实例uploadRequest
                    uploadRequest.Method      = WebRequestMethods.Ftp.UploadFile;                                              //将FtpWebRequest属性设置为上传文件
                    uploadRequest.Credentials = new NetworkCredential(AppConfig.FTPServerUserID, AppConfig.FTPServerPassword); //认证FTP用户名密码
                    requestStream             = uploadRequest.GetRequestStream();                                              //获得用于上传FTP的流
                    byte[] buffer = new byte[FileLength];
                    fileStream = file.OpenRead();                                                                              //.PostedFile.InputStream;//截取FileUpload获取的文件流,作为上传FTP的流
                    fileStream.Read(buffer, 0, FileLength);
                    requestStream.Write(buffer, 0, FileLength);                                                                //将buffer写入流
                    requestStream.Close();
                    uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();                                              //返回FTP服务器响应,上传完成
                                                                                                                               //上传成功
                }
                catch (Exception ex)
                {
                    //无法上传
                    return;
                }
                finally
                {
                    if (uploadResponse != null)
                    {
                        uploadResponse.Close();
                    }
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }
                    if (requestStream != null)
                    {
                        requestStream.Close();
                    }
                }
            }//end if #FileLength#
            else
            {
                //上传文件过大
                return;
            }
        }
コード例 #22
0
        /// <summary>
        /// 下载文件
        /// </summary>
        private void buttonDownload_Click(object sender, EventArgs e)
        {
            string fileName = GetSelectedFile();

            if (fileName.Length == 0)
            {
                MessageBox.Show("请先选择要下载的文件");
                return;
            }
            string filePath = Application.StartupPath + "\\DownLoad";

            if (Directory.Exists(filePath) == false)
            {
                Directory.CreateDirectory(filePath);
            }
            Stream       responseStream = null;
            FileStream   fileStream     = null;
            StreamReader reader         = null;

            try
            {
                string         uri      = GetUriString(fileName);
                FtpWebRequest  request  = CreateFtpWebRequest(uri, WebRequestMethods.Ftp.DownloadFile);
                FtpWebResponse response = GetFtpResponse(request);
                if (response == null)
                {
                    return;
                }
                responseStream = response.GetResponseStream();
                string path = filePath + "\\" + fileName;
                fileStream = File.Create(path);
                byte[] buffer = new byte[8196];
                int    bytesRead;
                while (true)
                {
                    bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    fileStream.Write(buffer, 0, bytesRead);
                }
                MessageBox.Show("下载完毕");
            }
            catch (UriFormatException err)
            {
                MessageBox.Show(err.Message);
            }
            catch (WebException err)
            {
                MessageBox.Show(err.Message);
            }
            catch (IOException err)
            {
                MessageBox.Show(err.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                else if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
コード例 #23
0
        private void CheckSFTP()
        {
            try{
                Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                //Dim Ftp1 As FTP
                string strIP      = string.Empty;
                string strCarpeta = string.Empty;
                string strUsers   = string.Empty;
                string strPass    = string.Empty;
                string strFile    = string.Empty;

                cpHTTP.cpHTTP_Clear();
                cpHTTP.cpHTTP_cadena1     = "Mike";
                cpHTTP.cpHTTP_sURL_cpCUCT = "https://ssl.e-pago.com.mx/pgs/jsp/cpagos/actualizador.jsp";

                if (cpHTTP.cpHTTP_SendcpCUCT())
                {
                    string strAux = string.Empty;
                    strAux     = cpHTTP.cpHTTP_sResult;
                    strIP      = Utils.Mid(strAux, 1, strAux.IndexOf("|"));
                    strAux     = Utils.Mid(strAux, strIP.Length + 2);
                    strCarpeta = Utils.Mid(strAux, 1, strAux.IndexOf("|"));
                    strAux     = Utils.Mid(strAux, strCarpeta.Length + 2);
                    strUsers   = Utils.Mid(strAux, 1, strAux.IndexOf("|"));
                    strAux     = Utils.Mid(strAux, strUsers.Length + 2);
                    strPass    = strAux.Trim();
                }

                try
                {
                    string host = "ftp://" + strIP;
                    Ftp1 = (FtpWebRequest)FtpWebRequest.Create(host);// + "/" + strCarpeta);
                    /* Log in to the FTP Server with the User Name and Password Provided */
                    Ftp1.Credentials = new NetworkCredential(strUsers, strPass);
                    /* When in doubt, use these options */

                    Ftp1.Method = WebRequestMethods.Ftp.DownloadFile;
                    /* Establish Return Communication with the FTP Server */
                    Ftpr = (FtpWebResponse)Ftp1.GetResponse();
                    /* Get the FTP Server's Response Stream */
                    Stream ftpStream = Ftpr.GetResponseStream();
                }
                catch { }
                Style img;
                if (Ftpr != null)
                {
                    //ImgSftpOK.Visibility = System.Windows.Visibility.Hidden;
                    //ImgSftpWarning.Visibility = System.Windows.Visibility.Hidden;
                    //ImgSftp.Visibility = System.Windows.Visibility.Hidden;
                    //ImgSftpNO.Visibility = System.Windows.Visibility.Visible;
                    CmdSFTP.Content = "Actualizar";
                    img             = FindResource("bien") as Style;
                    imagen3.Style   = img;
                }
                else
                {
                    //ImgSftpOK.Visibility = System.Windows.Visibility.Visible;
                    //ImgSftpWarning.Visibility = System.Windows.Visibility.Hidden;
                    //ImgSftp.Visibility = System.Windows.Visibility.Hidden;
                    //ImgSftpNO.Visibility = System.Windows.Visibility.Hidden;
                    CmdSFTP.Content = "Comprobar";
                    img             = FindResource("mal") as Style;
                    imagen3.Style   = img;
                }



                lbDescSFTP.Content = NBSFTP;

                //    Set Ftp1 = New FTP
                //    With Ftp1
                //        .Inicializar Me
                //        .PassWord = strPass
                //        .Usuario = strUsers
                //        .Servidor = strIP
                //        .CambiarDirectorio " & strCarpeta & "
                //        If .ConectarFtp(lbDescSFTP) = False Then
                //            ImgSftpOK.Visible = False
                //            ImgSftpWarning.Visible = False
                //            ImgSftp.Visible = False
                //            ImgSftpNO.Visible = True
                //        Else
                //            ImgSftpOK.Visible = True
                //            ImgSftpWarning.Visible = False
                //            ImgSftp.Visible = False
                //            ImgSftpNO.Visible = False
                //            CmdSFTP.Caption = "Actualizar"
                //        End If
                //    End With
                //    lbDescSFTP = NBSFTP
                //Exit Sub
            }
            catch (Exception Err) {
                System.Windows.MessageBox.Show("Descripcion: " + Err.Message, "Error");
                // MsgBox "Error: " & Err.Number & vbCrLf & "Descripcion: " & Err.Description, vbCritical, "MIT Update Para PcPay"
            }
            Mouse.OverrideCursor = null;
        }
コード例 #24
0
        public FtpClientResponse(FtpWebResponse response)
        {
            Response = response;

            StatusCode = response.StatusCode;
        }
コード例 #25
0
ファイル: ftptests.cs プロジェクト: JuanRiosJustus/docs
        //</snippet11>
        //<snippet8>
        public static bool ListFilesOnServerSsl(Uri serverUri)
        {
            // The serverUri should start with the ftp:// scheme.
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return(false);
            }
            // Get the object used to communicate with the server.
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);

            request.Method    = WebRequestMethods.Ftp.ListDirectory;
            request.EnableSsl = true;

            // Get the ServicePoint object used for this request, and limit it to one connection.
            // In a real-world application you might use the default number of connections (2),
            // or select a value that works best for your application.

            ServicePoint sp = request.ServicePoint;

            Console.WriteLine("ServicePoint connections = {0}.", sp.ConnectionLimit);
            sp.ConnectionLimit = 1;

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

            Console.WriteLine("The content length is {0}", response.ContentLength);
            // The following streams are used to read the data returned from the server.
            Stream       responseStream = null;
            StreamReader readStream     = null;

            try
            {
                responseStream = response.GetResponseStream();
                readStream     = new StreamReader(responseStream, System.Text.Encoding.UTF8);

                if (readStream != null)
                {
                    // Display the data received from the server.
                    Console.WriteLine(readStream.ReadToEnd());
                }
                Console.WriteLine("List status: {0}", response.StatusDescription);
            }
            finally
            {
                if (readStream != null)
                {
                    readStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }


            //<snippet12>
            Console.WriteLine("Banner message: {0}",
                              response.BannerMessage);
            //</snippet12>

            //<snippet13>
            Console.WriteLine("Welcome message: {0}",
                              response.WelcomeMessage);
            //</snippet13>

            //<snippet17>
            Console.WriteLine("Exit message: {0}",
                              response.ExitMessage);
            //</snippet17>
            return(true);
        }
コード例 #26
0
        private void m_btnUpload_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                UriBuilder    uri         = new UriBuilder("ftp", stSerOb.Host, 21, stSerOb.RemotePath);
                FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(uri.Uri);
                listRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
                listRequest.Credentials = credentials;
                listRequest.UsePassive  = false;
                List <string> lines   = new List <string>();
                string        uriPath = uri.Path;

                using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
                    using (Stream listStream = listResponse.GetResponseStream())
                        using (StreamReader listReader = new StreamReader(listStream))
                        {
                            while (!listReader.EndOfStream)
                            {
                                lines.Add(listReader.ReadLine());
                            }
                        }

                if (!Directory.Exists(stSerOb.LocalPath))
                {
                    DirectoryInfo directoryInfo = Directory.CreateDirectory(stSerOb.LocalPath);
                    if (!directoryInfo.Exists)
                    {
                        MessageBox.Show("Directory " + stSerOb.LocalPath + " cannot be created.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        Cursor.Current = Cursors.Default;
                    }
                }

                foreach (string line in lines)
                {
                    string name          = line;
                    string localFilePath = Path.Combine(stSerOb.LocalPath, name);
                    if (!System.IO.File.Exists(localFilePath))
                    {
                        uri.Path = uriPath + name;
                        UriBuilder    fileUri         = new UriBuilder(uri.Uri);
                        FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUri.Uri);
                        downloadRequest.UsePassive  = false;
                        downloadRequest.Method      = WebRequestMethods.Ftp.DownloadFile;
                        downloadRequest.Credentials = credentials;

                        using (FtpWebResponse downloadResponse =
                                   (FtpWebResponse)downloadRequest.GetResponse())
                            using (Stream sourceStream = downloadResponse.GetResponseStream())
                                using (Stream targetStream = System.IO.File.Create(localFilePath))
                                {
                                    byte[] buffer = new byte[10240];
                                    int    read;
                                    while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        targetStream.Write(buffer, 0, read);
                                    }
                                }
                    }
                }
            }
            catch (WebException ex)
            {
                String status = ((FtpWebResponse)ex.Response).StatusDescription;
                MessageBox.Show("Error by files download. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            Cursor.Current = Cursors.Default;
        }
コード例 #27
0
        public bool ListDirectory(out List <String> folderList, out List <String> fileList, string folderName = "")
        {
            _lastexception = null;
            bool          success = false;
            const string  dirDelimiterPattern = @"<DIR>";
            const string  fileDelimiterPattern = @" ";
            List <string> folders = new List <string>(), files = new List <string>();
            string        ErrorMessageHeader = string.Format(@"ListDirectory <{0}>", folderName);

            try
            {
                var request = CreateRequest(WebRequestMethods.Ftp.ListDirectoryDetails, folderName);

                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                {
                    var ftpstream = response.GetResponseStream();
                    {
                        if (null != ftpstream)
                        {
                            using (var txtreader = new StreamReader(ftpstream))
                            {
                                var line = string.Empty;
                                while (line != null)
                                {
                                    line = txtreader.ReadLine();
                                    if (!string.IsNullOrEmpty(line))
                                    {
                                        var dirSplit = Regex.Split(line, dirDelimiterPattern);
                                        if (dirSplit.Length == 2)
                                        {
                                            folders.Add(dirSplit[1].Trim());
                                        }
                                        else
                                        {
                                            //NOTE: Due to the limitatin of ftp, the remote file name can't be parsed correctly if contains white space
                                            var fileSplit = Regex.Split(line, fileDelimiterPattern);
                                            if (dirSplit.Length > 0)
                                            {
                                                files.Add(fileSplit[fileSplit.Count() - 1]);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                success = true;
            }
            catch (WebException webex)
            {
                _lastexception    = webex;
                _lastErrorMessage = string.Format(ErrorMessageFormat,
                                                  ErrorMessageHeader,
                                                  null != webex.InnerException ? webex.InnerException.Message : webex.Message,
                                                  webex.StackTrace);
            }
            catch (Exception ex)
            {
                _lastexception    = ex;
                _lastErrorMessage = string.Format(ErrorMessageFormat,
                                                  ErrorMessageHeader,
                                                  null != ex.InnerException ? ex.InnerException.Message : ex.Message,
                                                  ex.StackTrace);
            }

            if (_isBubbleUpException && null != _lastexception)
            {
                throw _lastexception;
            }

            folderList = folders;
            fileList   = files;

            return(success);
        }
コード例 #28
0
        public static string Upload(string pathToLocalFile, string ftpServer, string ftpUsername, string ftpPassword,
                                    string ftpSubfolder, string uniqueImage, string publicUriBase)
        {
            var fileName = Path.GetFileName(pathToLocalFile) + "";

            // Handle Unique Filename Upload
            if (!string.IsNullOrEmpty(uniqueImage))
            {
                fileName = uniqueImage;
            }

            var tmpFileName = fileName.Substring(0, fileName.Length - 2);
            var tempUri     = new Uri("ftp://" + ftpServer + "/" + ftpSubfolder + "/" + tmpFileName);

            var request = (FtpWebRequest)WebRequest.Create(tempUri);

            request.Proxy  = null;
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Authentication
            if (!string.IsNullOrEmpty(ftpUsername))
            {
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
            }

            // Copy the contents of the file to the request stream.
            var stream       = new FileStream(pathToLocalFile, FileMode.Open);
            var reader       = new BinaryReader(stream);
            var fileContents = reader.ReadBytes((int)stream.Length);

            stream.Close();
            reader.Close();

            request.ContentLength = fileContents.Length;
            try
            {
                var requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
            }
            catch (WebException e)
            {
                Console.WriteLine("error " + e.Message);
                // TODO Log
            }

            // Rename File
            FtpWebResponse response = null;

            try
            {
                response      = (FtpWebResponse)request.GetResponse();
                request       = (FtpWebRequest)WebRequest.Create(tempUri);
                request.Proxy = null;
                // Authentication
                if (!string.IsNullOrEmpty(ftpUsername))
                {
                    request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                }
                request.Method = WebRequestMethods.Ftp.Rename;

                request.RenameTo = fileName;
                response         = (FtpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                Console.WriteLine("error " + e.Message);
                // TODO Log
            }

            if (response != null)
            {
                Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
                response.Close();
            }

            return(publicUriBase + "/" + fileName);
        }
コード例 #29
0
    /* Rename File */
    public string rename(string currentFileNameAndPath, string newFileName)
    {
        string _result = null;

        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();
            
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.ToString());
            _result = ex.Message.ToString();
        }
        finally
        {
            /* Resource Cleanup */
            ftpResponse.Close();
            ftpRequest = null;
        }
        return _result;
    }
コード例 #30
0
        /// <summary>
        /// 下载文件,返回数据流
        /// </summary>
        /// <param name="p"></param>
        /// <param name="processsing"></param>
        /// <param name="end"></param>
        /// <param name="reserveObject"></param>
        /// <returns></returns>
        public MemoryStream DownLoadStream(FtpParameter p, Action <FTPStatusData> processsing, Action <FTPStatusData> end, object reserveObject)
        {
            try
            {
                string name = Common.ComFunc.FindFileName(p.FTP_URL);
                string dir  = p.FTP_URL;
                if (name.Length > 0)
                {
                    dir = dir.Replace(name, "");
                }

                //忽略文件名稱大小寫的處理
                //if (name.ToUpper() != name)
                //{
                //    name = FindMappingFileName(p);
                //}

                InitByParameters(p);

                ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse downloadResponse =
                    (FtpWebResponse)ftpRequest.GetResponse();

                stream = downloadResponse.GetResponseStream();

                string fileName =
                    Path.GetFileName(ftpRequest.RequestUri.AbsolutePath);

                MemoryStream rtn = null;
                if (fileName.Length == 0)
                {
                    rtn = new MemoryStream();
                }
                else
                {
                    //如果有指定文件名称
                    rtn = new MemoryStream();

                    byte[] buffer = new byte[p.BufferSize];
                    int    bytesRead;
                    long   transfer  = 0;
                    double speed     = 0;
                    var    st        = DateTime.Now;
                    var    totalbyte = fileStream.Length;
                    while (true)
                    {
                        bytesRead = stream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                        {
                            break;
                        }
                        rtn.Write(buffer, 0, bytesRead);

                        transfer += bytesRead;


                        if (processsing != null)
                        {
                            var fsd = new FTPStatusData();
                            fsd.CurrentByteLength    = bytesRead;
                            fsd.TransferedByteLength = transfer;
                            fsd.TotalByteLength      = totalbyte;
                            fsd.FileName             = Path.GetFileName(name);
                            fsd.CostTime             = DateTime.Now - st;
                            var s = fsd.CostTime.TotalMilliseconds;
                            if (s != 0)
                            {
                                speed = (double)transfer / s * 1000;
                            }
                            fsd.Speed         = speed;
                            fsd.CurrentStatus = FTPStatusData.FtpStaus.Processing;
                            fsd.ReserveObject = reserveObject;

                            processsing(fsd);
                        }
                    }

                    if (end != null)
                    {
                        var fsd = new FTPStatusData();
                        fsd.CurrentByteLength    = bytesRead;
                        fsd.TransferedByteLength = transfer;
                        fsd.TotalByteLength      = totalbyte;
                        fsd.FileName             = Path.GetFileName(name);
                        fsd.CostTime             = DateTime.Now - st;
                        var s = fsd.CostTime.TotalMilliseconds;
                        if (s != 0)
                        {
                            speed = (double)transfer / s * 1000;
                        }
                        fsd.Speed         = speed;
                        fsd.CurrentStatus = FTPStatusData.FtpStaus.End;
                        fsd.ReserveObject = reserveObject;

                        end(fsd);
                    }
                }

                return(rtn);
            }
            finally
            {
                Release();
            }
        }
コード例 #31
0
        public void CreateFilesLesson(string namefile, string namelesson, IFormFile pathfile, string links, string text, int countlesson)// создаем файлы урока
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://141.8.193.236/" + namefile + "/" + namelesson + "_" + countlesson);

            request.Method      = WebRequestMethods.Ftp.MakeDirectory;
            request.Credentials = new NetworkCredential("f0442011", "uztuasismi");
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            //загружаем файл
            string path = @"C:\Users\Люда\Desktop\Крсовая 3 курс\Project\Project\wwwroot\file\" + countlesson + "_" + pathfile.FileName;

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                pathfile.CopyToAsync(fileStream);
            }
            FtpWebRequest request_1 = (FtpWebRequest)WebRequest.Create("ftp://141.8.193.236/" + namefile + "/" + countlesson + "_" + pathfile.FileName);

            request_1.Credentials = new NetworkCredential("f0442011", "uztuasismi");
            request_1.Method      = WebRequestMethods.Ftp.UploadFile;
            FileStream fs_1 = new FileStream(path, FileMode.Open);

            byte[] fileContents_1 = new byte[fs_1.Length];
            fs_1.Read(fileContents_1, 0, fileContents_1.Length);
            fs_1.Close();
            request_1.ContentLength = fileContents_1.Length;
            Stream requestStream_1 = request_1.GetRequestStream();

            requestStream_1.Write(fileContents_1, 0, fileContents_1.Length);
            requestStream_1.Close();
            FtpWebResponse response_0 = (FtpWebResponse)request_1.GetResponse();

            File.Delete(path);
            //загружаем текстовый файл с информацией
            string writePath = "Info" + countlesson + ".txt";

            using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding.Default))
            {
                sw.WriteLine(text);
            }
            FtpWebRequest request_2 = (FtpWebRequest)WebRequest.Create("ftp://141.8.193.236/" + namefile + "/" + namelesson + "_" + countlesson + "_" + writePath);

            request_2.Credentials = new NetworkCredential("f0442011", "uztuasismi");
            request_2.Method      = WebRequestMethods.Ftp.UploadFile;
            FileStream fs = new FileStream(writePath, FileMode.Open);

            byte[] fileContents = new byte[fs.Length];
            fs.Read(fileContents, 0, fileContents.Length);
            fs.Close();
            request_2.ContentLength = fileContents.Length;
            Stream requestStream = request_2.GetRequestStream();

            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            FtpWebResponse response_1 = (FtpWebResponse)request_2.GetResponse();

            File.Delete(writePath);
            // загружаем файл с ссылкой на видео
            string linkpath = "Link" + countlesson + ".txt";

            using (StreamWriter sw_3 = new StreamWriter(linkpath, false, System.Text.Encoding.Default))
            {
                sw_3.WriteLine(links);
            }
            FtpWebRequest request_3 = (FtpWebRequest)WebRequest.Create("ftp://141.8.193.236/" + namefile + "/" + namelesson + "_" + countlesson + "_" + linkpath);

            request_3.Credentials = new NetworkCredential("f0442011", "uztuasismi");
            request_3.Method      = WebRequestMethods.Ftp.UploadFile;
            FileStream fs_3 = new FileStream(linkpath, FileMode.Open);

            byte[] fileContents_3 = new byte[fs_3.Length];
            fs_3.Read(fileContents_3, 0, fileContents_3.Length);
            fs_3.Close();
            request_3.ContentLength = fileContents_3.Length;
            Stream requestStream_3 = request_3.GetRequestStream();

            requestStream_3.Write(fileContents_3, 0, fileContents_3.Length);
            requestStream_3.Close();
            FtpWebResponse response_3 = (FtpWebResponse)request_3.GetResponse();

            File.Delete(linkpath);
        }
コード例 #32
0
        /// <summary>
        /// Uploads a file if it does not yet exist, or if it is newer than the <code>destinationFile</code>.
        /// </summary>
        private void UploadFile(string sourceFile, string destinationFile)
        {
            bool     write = false;
            DateTime destinationFileLastModified = DateTime.Today;
            DateTime sourceFileLastModified      = DateTime.Today;
            long     destinationSize             = 0;
            long     sourceSize = 0;

            // Get the DateTimeStamp of the destinationFile.
            FtpWebRequest request = SetupFtpWebRequest(destinationFile, WebRequestMethods.Ftp.GetDateTimestamp);

            try
            {
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                destinationFileLastModified = response.LastModified;
            }
            catch (WebException ex)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                // File does not exist: create
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    OnProgress("File " + destinationFile + " does not yet exist. Adding...", _currentFile, _totalFiles);
                    write = true;
                }
            }

            if (!write)
            {
                // Get the DateTimeStamp of the sourceFile.
                FileInfo fi = new FileInfo(sourceFile);
                sourceFileLastModified = fi.LastWriteTime;

                if (sourceFileLastModified > destinationFileLastModified)
                {
                    OnProgress("File " + destinationFile + " already exists, but newer version found... Replacing...", _currentFile, _totalFiles);
                    write = true;
                }
                else
                {
                    // Compare size
                    // Destination file
                    request = SetupFtpWebRequest(destinationFile, WebRequestMethods.Ftp.GetFileSize);
                    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                    destinationSize = response.ContentLength;

                    // Source file
                    sourceSize = fi.Length;

                    if (sourceSize != destinationSize)
                    {
                        OnProgress("File " + destinationFile + " already exists, but of different size... Replacing...", _currentFile, _totalFiles);
                        write = true;
                    }
                }
            }

            if (write)
            {
                request = SetupFtpWebRequest(destinationFile, WebRequestMethods.Ftp.UploadFile);

                FileStream stream = File.OpenRead(sourceFile);
                byte[]     buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                Stream reqStream = request.GetRequestStream();
                try
                {
                    reqStream.Write(buffer, 0, buffer.Length);
                }
                finally
                {
                    reqStream.Close();
                }
            }
            else
            {
                OnProgress("File " + destinationFile + " already exists. Skipping...", _currentFile, _totalFiles);
            }
        }
コード例 #33
0
        static void Main(string[] args)
        {
            string command;
            bool   quitNow      = false;
            string finalpath    = serverpath + "RARROrderSample.edi";
            string downloadpath = localpath + "RARROrderSample.edi";

            Console.WriteLine(@" ____  _____ ____  _     ____  _____   ____  ____  ____  _____");
            Console.WriteLine(@"/ ___\/  __//   _\/ \ /\/  __\/  __/  /   _\/  _ \/  __\/  __/");
            Console.WriteLine(@"|    \|  \  |  /  | | |||  \/||  \    |  /  | / \||  \/||  \  ");
            Console.WriteLine(@"\___ ||  /_ |  \__| \_/||    /|  /_   |  \__| \_/||    /|  /_ ");
            Console.WriteLine(@"\____/\____\\____/\____/\_/\_\\____\  \____/\____/\_/\_\\____\");
            Console.WriteLine(@"                                                             ");
            Console.WriteLine(@"            __              ");
            Console.WriteLine(@"|\/|||  |  |_ |\ ||/  \|\/| ");
            Console.WriteLine(@"|  |||__|__|__| \||\__/|  | ");
            Console.WriteLine(@"       __ __  __  __        ");
            Console.WriteLine(@"      /  /  \|  \|_         ");
            Console.WriteLine(@"      \__\__/|__/|__        ");
            Console.WriteLine(@"                            ");
            Console.WriteLine(@"                            ");
            Console.WriteLine(@"                            ");
            Console.WriteLine(@"For more information /help");

            while (!quitNow)
            {
                command = Console.ReadLine();
                switch (command)
                {
                case "/help":
                    Console.WriteLine("/search          Search for EDI files.");
                    Console.WriteLine("/download        Download data.");
                    Console.WriteLine("/quit            Exit console.");
                    break;

                case "/search":
                    Console.WriteLine("Searching...");
                    // Get the object used to communicate with the server.
                    FtpWebRequest searchrequest = (FtpWebRequest)WebRequest.Create(string.Format("ftp://{0}/{1}", strServer, finalpath));
                    searchrequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

                    // This example assumes the FTP site uses anonymous logon.
                    searchrequest.Credentials = new NetworkCredential(strUser, strPassword);

                    FtpWebResponse response = (FtpWebResponse)searchrequest.GetResponse();

                    Stream       responseStream = response.GetResponseStream();
                    StreamReader reader         = new StreamReader(responseStream);
                    Console.WriteLine(@"Files found:");
                    Console.WriteLine(reader.ReadToEnd());

                    reader.Close();
                    response.Close();
                    break;

                case "/download":

                    Console.WriteLine(@"Reading files...");
                    FtpWebRequest downloadrequest = (FtpWebRequest)WebRequest.Create(string.Format("ftp://{0}/{1}", strServer, finalpath));

                    //Set proxy to null. Under current configuration if this option is not set then the proxy that is used will get an html response from the web content gateway (firewall monitoring system)
                    downloadrequest.Proxy = null;

                    downloadrequest.UsePassive = true;
                    downloadrequest.UseBinary  = true;

                    downloadrequest.Credentials = new NetworkCredential(strUser, strPassword);

                    int    bytesRead = 0;
                    byte[] buffer    = new byte[2048];

                    downloadrequest.Method = WebRequestMethods.Ftp.DownloadFile;

                    Stream     downloadreader = downloadrequest.GetResponse().GetResponseStream();
                    FileStream fileStream     = new FileStream(downloadpath, FileMode.Create);

                    while (true)
                    {
                        bytesRead = downloadreader.Read(buffer, 0, buffer.Length);

                        if (bytesRead == 0)
                        {
                            break;
                        }

                        fileStream.Write(buffer, 0, bytesRead);
                    }
                    fileStream.Close();
                    Console.WriteLine("File downloaded.");
                    break;

                case "/quit":
                    Console.WriteLine(@"Bye :)");
                    quitNow = true;
                    break;

                default:
                    Console.WriteLine("Unknown Command " + command);
                    break;
                }
            }
        }
コード例 #34
0
        /// <summary>
        /// 上传文件到FTP服务器
        /// </summary>
        /// <param name="localFullPath">本地带有完整路径的文件名</param>
        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
        /// <returns>是否下载成功</returns>
        public static bool FtpUploadFile(string localFullPathName, Action <int, int> updateProgress = null)
        {
            FtpWebRequest  reqFTP;
            Stream         stream   = null;
            FtpWebResponse response = null;
            FileStream     fs       = null;

            try
            {
                FileInfo finfo = new FileInfo(localFullPathName);
                if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
                {
                    throw new Exception("ftp上传目标服务器地址未设置!");
                }
                Uri uri = new Uri("ftp://" + FtpServerIP + "/" + finfo.Name);
                reqFTP               = (FtpWebRequest)FtpWebRequest.Create(uri);
                reqFTP.KeepAlive     = false;
                reqFTP.UseBinary     = true;
                reqFTP.Credentials   = new NetworkCredential(FtpUserID, FtpPassword); //用户,密码
                reqFTP.Method        = WebRequestMethods.Ftp.UploadFile;              //向服务器发出下载请求命令
                reqFTP.ContentLength = finfo.Length;                                  //为request指定上传文件的大小
                response             = reqFTP.GetResponse() as FtpWebResponse;
                reqFTP.ContentLength = finfo.Length;
                int    buffLength = 1024;
                byte[] buff       = new byte[buffLength];
                int    contentLen;
                fs         = finfo.OpenRead();
                stream     = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                int allbye = (int)finfo.Length;
                //更新进度
                if (updateProgress != null)
                {
                    updateProgress((int)allbye, 0);//更新进度条
                }
                int startbye = 0;
                while (contentLen != 0)
                {
                    startbye = contentLen + startbye;
                    stream.Write(buff, 0, contentLen);
                    //更新进度
                    if (updateProgress != null)
                    {
                        updateProgress((int)allbye, (int)startbye);//更新进度条
                    }
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                stream.Close();
                fs.Close();
                response.Close();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);

                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
                if (stream != null)
                {
                    stream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
コード例 #35
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="p"></param>
        /// <param name="fileStream"></param>
        /// <param name="processsing">上传过程中的处理事件</param>
        /// <param name="end">上传完成的处理事件</param>
        /// <param name="reserveObject">传入的保留参数对象</param>
        public void Upload(FtpParameter p, Stream fileStream, Action <FTPStatusData> processsing, Action <FTPStatusData> end, object reserveObject)
        {
            try
            {
                FtpCheckDirectoryExist(p);
                InitByParameters(p);

                ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

                // UploadFile is not supported through an Http proxy
                // so we disable the proxy for this request.
                ftpRequest.Proxy = null;

                stream = ftpRequest.GetRequestStream();

                byte[] buffer = new byte[p.BufferSize];
                int    bytesRead;
                long   transfer  = 0;
                double speed     = 0;
                var    st        = DateTime.Now;
                var    totalbyte = fileStream.Length;
                while (true)
                {
                    bytesRead = fileStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    stream.Write(buffer, 0, bytesRead);

                    transfer += bytesRead;


                    if (processsing != null)
                    {
                        var fsd = new FTPStatusData();
                        fsd.CurrentByteLength    = bytesRead;
                        fsd.TransferedByteLength = transfer;
                        fsd.TotalByteLength      = totalbyte;
                        fsd.FileName             = Path.GetFileName(p.FTP_URL);
                        fsd.CostTime             = DateTime.Now - st;
                        var s = fsd.CostTime.TotalMilliseconds;
                        if (s != 0)
                        {
                            speed = (double)transfer / s * 1000;
                        }
                        fsd.Speed         = speed;
                        fsd.CurrentStatus = FTPStatusData.FtpStaus.Processing;
                        fsd.ReserveObject = reserveObject;

                        processsing(fsd);
                    }
                }

                // The request stream must be closed before getting
                // the response.
                stream.Close();

                ftpResponse =
                    (FtpWebResponse)ftpRequest.GetResponse();

                if (end != null)
                {
                    var fsd = new FTPStatusData();
                    fsd.CurrentByteLength    = bytesRead;
                    fsd.TransferedByteLength = transfer;
                    fsd.TotalByteLength      = totalbyte;
                    fsd.FileName             = Path.GetFileName(p.FTP_URL);
                    fsd.CostTime             = DateTime.Now - st;
                    var s = fsd.CostTime.TotalMilliseconds;
                    if (s != 0)
                    {
                        speed = (double)transfer / s * 1000;
                    }
                    fsd.Speed         = speed;
                    fsd.CurrentStatus = FTPStatusData.FtpStaus.End;
                    fsd.ReserveObject = reserveObject;

                    end(fsd);
                }
            }
            finally
            {
                Release();
            }
        }
コード例 #36
0
        /// <summary>
        /// 从FTP服务器下载文件,指定本地路径和本地文件名
        /// </summary>
        /// <param name="remoteFileName">远程文件名</param>
        /// <param name="localFileName">保存本地的文件名(包含路径)</param>
        /// <param name="ifCredential">是否启用身份验证(false:表示允许用户匿名下载)</param>
        /// <param name="updateProgress">报告进度的处理(第一个参数:总大小,第二个参数:当前进度)</param>
        /// <returns>是否下载成功</returns>
        public static bool FtpDownload(string remoteFileName, string localFileName, bool ifCredential, Action <int, int> updateProgress = null)
        {
            FtpWebRequest  reqFTP, ftpsize;
            Stream         ftpStream    = null;
            FtpWebResponse response     = null;
            FileStream     outputStream = null;

            try
            {
                outputStream = new FileStream(localFileName, FileMode.Create);
                if (FtpServerIP == null || FtpServerIP.Trim().Length == 0)
                {
                    throw new Exception("ftp下载目标服务器地址未设置!");
                }
                Uri uri = new Uri("ftp://" + FtpServerIP + "/" + remoteFileName);
                ftpsize           = (FtpWebRequest)FtpWebRequest.Create(uri);
                ftpsize.UseBinary = true;

                reqFTP           = (FtpWebRequest)FtpWebRequest.Create(uri);
                reqFTP.UseBinary = true;
                reqFTP.KeepAlive = false;
                if (ifCredential)//使用用户身份认证
                {
                    ftpsize.Credentials = new NetworkCredential(FtpUserID, FtpPassword);
                    reqFTP.Credentials  = new NetworkCredential(FtpUserID, FtpPassword);
                }
                ftpsize.Method = WebRequestMethods.Ftp.GetFileSize;
                FtpWebResponse re         = (FtpWebResponse)ftpsize.GetResponse();
                long           totalBytes = re.ContentLength;
                re.Close();

                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                response      = (FtpWebResponse)reqFTP.GetResponse();
                ftpStream     = response.GetResponseStream();

                //更新进度
                if (updateProgress != null)
                {
                    updateProgress((int)totalBytes, 0);//更新进度条
                }
                long   totalDownloadedByte = 0;
                int    bufferSize          = 2048;
                int    readCount;
                byte[] buffer = new byte[bufferSize];
                readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    totalDownloadedByte = readCount + totalDownloadedByte;
                    outputStream.Write(buffer, 0, readCount);
                    //更新进度
                    if (updateProgress != null)
                    {
                        updateProgress((int)totalBytes, (int)totalDownloadedByte);//更新进度条
                    }
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);

                throw;
            }
            finally
            {
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }
コード例 #37
0
	/* Create a New Directory on the FTP Server */
	public void createDirectory(string newDirectory)
	{
		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) { Console.WriteLine(ex.ToString()); }
		return;
	}
コード例 #38
0
        static public string DownLoad(FtpFile ftpfile, string outputpath)
        {
            Stream         responseStream = null;
            FileStream     stream2        = null;
            FtpWebResponse response       = null;
            string         message;

            try
            {
                if (ftpfile != null)
                {
                    string ftpPath   = "ftp://" + FtpIp + ftpfile.FilePath;
                    string outPutDir = Path.GetDirectoryName(outputpath);
                    if (!Directory.Exists(outPutDir))
                    {
                        Directory.CreateDirectory(outPutDir);
                    }
                    stream2 = new FileStream(outputpath, FileMode.Create);
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(ftpPath));
                    request.Method      = "RETR";
                    request.UseBinary   = true;
                    request.KeepAlive   = false;
                    request.Credentials = new NetworkCredential(FtpUserName, FtpUserPwd);
                    response            = (FtpWebResponse)request.GetResponse();
                    responseStream      = response.GetResponseStream();
                    byte[] buffer = new byte[0x800];
                    if (responseStream != null)
                    {
                        for (int i = responseStream.Read(buffer, 0, 0x800); i > 0; i = responseStream.Read(buffer, 0, 0x800))
                        {
                            stream2.Write(buffer, 0, i);
                        }
                        responseStream.Close();
                    }
                    stream2.Close();
                    response.Close();
                    return("下载成功");
                }
                message = "没有需要下载的文件";
            }
            catch (Exception exception)
            {
                message = exception.Message;
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (stream2 != null)
                {
                    stream2.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return(message);
        }
コード例 #39
0
        //
        /// <summary>
        /// 从ftp服务器下载文件的功能----带进度条
        /// </summary>
        /// <param name="ftpfilepath">ftp下载的地址</param>
        /// <param name="filePath">保存本地的地址</param>
        /// <param name="fileName">保存的名字</param>
        /// <param name="pb">进度条引用</param>
        /// <returns></returns>
        public static bool Download(string ftpfilepath, string filePath, string fileName, ProgressBar pb)
        {
            FtpWebRequest  reqFtp       = null;
            FtpWebResponse response     = null;
            Stream         ftpStream    = null;
            FileStream     outputStream = null;

            try
            {
                filePath = filePath.Replace("我的电脑\\", "");
                String onlyFileName = Path.GetFileName(fileName);
                string newFileName  = filePath + onlyFileName;
                if (File.Exists(newFileName))
                {
                    try
                    {
                        File.Delete(newFileName);
                    }
                    catch { }
                }
                ftpfilepath = ftpfilepath.Replace("\\", "/");
                string url = FTPCONSTR + ftpfilepath;
                reqFtp             = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
                reqFtp.UseBinary   = true;
                reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
                response           = (FtpWebResponse)reqFtp.GetResponse();
                ftpStream          = response.GetResponseStream();
                long   cl         = GetFileSize(url);
                int    bufferSize = 2048;
                int    readCount;
                byte[] buffer = new byte[bufferSize];
                readCount    = ftpStream.Read(buffer, 0, bufferSize);
                outputStream = new FileStream(newFileName, FileMode.Create);

                float percent = 0;
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    percent   = (float)outputStream.Length / (float)cl * 100;
                    if (percent <= 100)
                    {
                        if (pb != null)
                        {
                            pb.Invoke(new updateui(upui), new object[] { cl, (int)percent, pb });
                        }
                    }
                    // pb.Invoke(new updateui(upui), new object[] { cl, outputStream.Length, pb });
                }

                //MessageBoxEx.Show("Download0");
                return(true);
            }
            catch (Exception ex)
            {
                //errorinfo = string.Format("因{0},无法下载", ex.Message);
                //MessageBoxEx.Show("Download00");
                return(false);
            }
            finally
            {
                //MessageBoxEx.Show("Download2");
                if (reqFtp != null)
                {
                    reqFtp.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (ftpStream != null)
                {
                    ftpStream.Close();
                }
                if (outputStream != null)
                {
                    outputStream.Close();
                }
            }
        }
コード例 #40
0
ファイル: ftp.cs プロジェクト: kidass/gitContact
            // 获取ftp命令执行的响应信息
            private WebResponse GetFtpResponse()
            {
                FtpWebResponse ftpresponse = null;
                ResponseDescription resp_desc = null;
                Socket objNewDataConnection = null;
                Socket DataConnection = null;

                // 根据命令类型执行PASV或PORT命令
                switch (m_CommandType)
                {
                    case FtpCommandType.FtpDataReceiveCommand:
                    case FtpCommandType.FtpDataSendCommand:
                        if (m_bPassiveMode)
                            OpenPassiveDataConnection();
                        else
                            OpenDataConnection();
                        break;
                    default:
                        break;
                }

                // 设置传输方式
                // A - ascii  (文本)
                // I - binary (二进制 - 缺省)
                string sztype = "I";
                if (m_szContentType != null)
                    if (m_szContentType.ToLower() == "ascii")
                        sztype = "A";
                SendCommand("TYPE", sztype);
                resp_desc = ReceiveCommandResponse();
                if (!resp_desc.PositiveCompletion)
                    throw new System.ApplicationException("Error: Data negotiation failed.\r\n" + m_sbControlSocketLog.ToString());

                // 执行请求的FTP操作
                switch (m_szServerMethod)
                {
                    case "PWD":
                        // 打印工作目录
                        m_szCmdParameter = null;
                        SendCommand(m_szServerMethod, m_szCmdParameter);
                        resp_desc = ReceiveCommandResponse();
                        break;
                    case "REN":
                        // 更改文件名
                        // 1. 转到指定目录
                        SendCommand("CWD", m_szCmdParameter);
                        resp_desc = ReceiveCommandResponse();
                        if (resp_desc.Status != 550)
                        {
                            // 2. 执行RNFR命令
                            SendCommand("RNFR", m_szFromFile);
                            resp_desc = ReceiveCommandResponse();
                            if (resp_desc.Status != 550)
                            {
                                // 3. 执行RNTO命令
                                SendCommand("RNTO", m_szToFile);
                                resp_desc = ReceiveCommandResponse();
                            }
                        }
                        break;
                    default:
                        // 其他FTP操作
                        SendCommand(m_szServerMethod, m_szCmdParameter);
                        resp_desc = ReceiveCommandResponse();
                        break;
                }

                // 执行操作后,对响应进行分析
                try
                {
                    if (m_CommandType == FtpCommandType.FtpDataSendCommand)
                    {
                        // 上传数据
                        if (resp_desc.PositivePreliminary)
                        {
                            // 服务器准备接收上传数据
                            if (m_RequestStream != null)
                            {
                                // 获取数据连接
                                if (m_bPassiveMode)
                                {
                                    DataConnection = m_DataSocket;
                                    objNewDataConnection = null;
                                }
                                else
                                {
                                    DataConnection = m_DataSocket.Accept();
                                    objNewDataConnection = DataConnection;
                                }
                                if (DataConnection == null)
                                    throw new System.Net.ProtocolViolationException("Error: can not build data connectios!");

                                // 上载处理
                                try
                                {
                                    // 发送数据
                                    SendData(DataConnection);

                                    // 关闭数据连接,以获取服务器的完毕响应
                                    SafeRelease(ref DataConnection);

                                    //[完毕响应]与[开始上载]响应同时获得!
                                    if (resp_desc.StatusDescription.IndexOf("\r\n226", 0) != -1)
                                    {
                                        //文件传输完毕
                                        resp_desc.Status = 226;
                                        ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
                                    }
                                    else
                                    {
                                        // 等待[文件传输完毕]响应
                                        ResponseDescription resp = ReceiveCommandResponse();
                                        ftpresponse = new FtpWebResponse(resp.Status, resp.StatusDescription, m_sbControlSocketLog.ToString());
                                    }
                                }
                                catch (Exception e)
                                {
                                    throw e;
                                }
                            }
                            else
                                throw new System.ApplicationException("Error: Data to be uploaded not specified!");
                        }
                        else
                            throw new System.ApplicationException(ComposeExceptionMessage(resp_desc, m_sbControlSocketLog.ToString()));
                    }
                    else if (m_CommandType == FtpCommandType.FtpDataReceiveCommand)
                    {
                        // 下载数据
                        if (resp_desc.PositivePreliminary)
                        {
                            // 获取数据连接
                            if (m_bPassiveMode)
                            {
                                DataConnection = m_DataSocket;
                                objNewDataConnection = null;
                            }
                            else
                            {
                                DataConnection = m_DataSocket.Accept();
                                objNewDataConnection = DataConnection;
                            }
                            if (DataConnection == null)
                                throw new System.Net.ProtocolViolationException("Error: can not build data connectios!");

                            // 下载处理
                            Stream datastream = null;
                            try
                            {
                                // 获取命令响应信息
                                if (resp_desc.StatusDescription.IndexOf("\r\n550", 0) != -1)
                                {
                                    // 源文件不存在!
                                    resp_desc.Status = 550;
                                    ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
                                }
                                else if (resp_desc.StatusDescription.IndexOf("\r\n226", 0) != -1)
                                {
                                    // 小文件情况 - 数据下载完毕!
                                    switch (m_szServerMethod)
                                    {
                                        case "LIST":
                                            // 不创建流
                                            resp_desc.Status = 226;
                                            ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
                                            break;
                                        default:
                                            datastream = ReceiveData(DataConnection);
                                            resp_desc.Status = 226;
                                            ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
                                            ftpresponse.SetDownloadStream(datastream);
                                            break;
                                    }
                                }
                                else
                                {

                                    // 大文件情况 - 需要最后获取[数据下载完毕]的响应
                                    datastream = ReceiveData(DataConnection);
                                    ResponseDescription resp = ReceiveCommandResponse();
                                    ftpresponse = new FtpWebResponse(resp.Status, resp.StatusDescription, m_sbControlSocketLog.ToString());
                                    ftpresponse.SetDownloadStream(datastream);

                                }
                            }
                            catch (Exception e)
                            {
                                SafeRelease(ref datastream);
                                throw e;
                            }
                        }
                        else
                            throw new ApplicationException(ComposeExceptionMessage(resp_desc, m_sbControlSocketLog.ToString()));
                    }
                    else
                        ftpresponse = new FtpWebResponse(resp_desc.Status, resp_desc.StatusDescription, m_sbControlSocketLog.ToString());
                }
                catch (Exception e)
                {
                    SafeRelease(ref objNewDataConnection);
                    CloseDataConnection();
                    throw e;
                }

                SafeRelease(ref objNewDataConnection);
                CloseDataConnection();

                return ftpresponse;
            }