示例#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 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;
    }
示例#3
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[] { "" };
	}
示例#4
0
    /* List Directory Contents File/Folder Name Only */
    public async Task <string[]> DirectoryList(string directory)
    {
        try
        {
            _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + directory);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = true;
            _ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
            using (_ftpResponse = (FtpWebResponse)await _ftpRequest.GetResponseAsync())
            {
                using (_ftpStream = _ftpResponse.GetResponseStream())
                {
                    if (_ftpStream != null)
                    {
                        var    ftpReader    = new StreamReader(_ftpStream);
                        string directoryRaw = null;
                        try
                        {
                            while (ftpReader.Peek() != -1)
                            {
                                directoryRaw += ftpReader.ReadLine() + "|";
                            }
                        }
                        finally
                        {
                            ftpReader?.Close();
                            _ftpStream?.Close();
                            _ftpResponse?.Close();
                            _ftpRequest = null;
                        }

                        if (directoryRaw != null)
                        {
                            var directoryList = directoryRaw.Split("|".ToCharArray());
                            return(directoryList);
                        }
                    }
                }
            }
        }
        finally
        {
            _ftpResponse?.Close();
            _ftpRequest = null;
        }

        /* Return an Empty string Array if an Exception exception Occurs */
        return(new[] { "" });
    }
        /// <summary>
        /// 从ftp服务器删除文件的功能
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool DeleteFile(string fileName)
        {
            var            url      = _ftpconstr + fileName;
            FtpWebResponse response = null;

            try
            {
                var reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(url));
                reqFtp.UseBinary   = true;
                reqFtp.KeepAlive   = false;
                reqFtp.Method      = WebRequestMethods.Ftp.DeleteFile;
                reqFtp.Credentials = new NetworkCredential(_ftpusername, _ftppassword);
                response           = (FtpWebResponse)reqFtp.GetResponse();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("因{0},无法删除文件", ex.Message);
                return(false);
            }
            finally
            {
                response?.Close();
            }
        }
示例#6
0
        private bool _coreFileExists(string path, int responseTimeOut)
        {
            var request     = CreateWebRequest(path, WebRequestMethods.Ftp.GetFileSize);
            var asyncResult = request.BeginGetResponse(null, null);
            var result      = false;

            if (asyncResult.AsyncWaitHandle.WaitOne(responseTimeOut, false))
            {
                FtpWebResponse response = null;
                try
                {
                    response = (FtpWebResponse)request.EndGetResponse(asyncResult);
                    result   = true;
                }
                catch (WebException)
                { }
                finally
                { response?.Close(); }
            }
            else
            {
                request.Abort();
                throw new WebException(string.Empty, WebExceptionStatus.Timeout);
            }

            return(result);
        }
示例#7
0
        //---------------------------------------------------------------------
        private void _coreDownloadFile(string path, string pathToLocalMachine, int responseTimeOut, int bufferLength)
        {
            var webRequest  = CreateWebRequest(path, WebRequestMethods.Ftp.DownloadFile);
            var asyncResult = webRequest.BeginGetResponse(null, null);

            if (asyncResult.AsyncWaitHandle.WaitOne(responseTimeOut, false))
            {
                FtpWebResponse webResponse = null;
                try
                {
                    webResponse = (FtpWebResponse)webRequest.EndGetResponse(asyncResult);
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        using (var fileStream = LocalMachineCreateFileStream(pathToLocalMachine))
                        { CopyStreams(responseStream, fileStream, bufferLength); }
                    }
                }
                finally
                { webResponse?.Close(); }
            }
            else
            {
                webRequest.Abort();
                throw new WebException(string.Empty, WebExceptionStatus.Timeout);
            }
        }
示例#8
0
        bool IsDirectoryAlreadyPresentStandardFtp(IActivityIOPath path)
        {
            FtpWebResponse response = null;

            bool isAlive;

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(path.Path));
                request.Method    = WebRequestMethods.Ftp.ListDirectory;
                request.UseBinary = true;
                request.KeepAlive = false;
                request.EnableSsl = EnableSsl(path);

                if (path.Username != string.Empty)
                {
                    request.Credentials = new NetworkCredential(path.Username, path.Password);
                }

                if (path.IsNotCertVerifiable)
                {
                    ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                }

                using (response = (FtpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (StreamReader reader = new StreamReader(responseStream))
                            {
                                if (reader.EndOfStream)
                                {
                                    // just check for exception, slow I know, but not sure how else to tackle this
                                }
                            }
                        }
                    }
                }

                // exception will be thrown if not present
                isAlive = true;
            }
            catch (WebException wex)
            {
                Dev2Logger.Error(this, wex);
                isAlive = false;
            }
            catch (Exception ex)
            {
                Dev2Logger.Error(this, ex);
                throw;
            }
            finally
            {
                response?.Close();
            }
            return(isAlive);
        }
示例#9
0
    public async Task CreateDirectoryAsync(string newDirectory)
    {
        try
        {
            var remoteFilePathResult = PrepareRemoteFilePath(Os.Linux, _host, newDirectory);

            if (remoteFilePathResult.IsFailure)
            {
                return;
            }

            _ftpRequest             = (FtpWebRequest)WebRequest.Create(remoteFilePathResult.Value);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = true;
            _ftpRequest.Method      = WebRequestMethods.Ftp.MakeDirectory;
            _ftpResponse            = (FtpWebResponse)await _ftpRequest.GetResponseAsync();
        }
        finally
        {
            _ftpResponse?.Close();
            _ftpRequest = null;
        }
    }
示例#10
0
        /// <summary>
        ///     Remotes the FTP dir exists.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool RemoteFtpDirExists(string address)
        {
            var req = (FtpWebRequest)WebRequest.Create(address);

            req.Method = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse res = null;

            try
            {
                res = (FtpWebResponse)req.GetResponse();
                var code = res.StatusCode;
                res.Close();
                return(true);
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e);
                res?.Close();
                return(false);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw e;
            }
        }
示例#11
0
    /* Get the Date/Time a File was Created */
    public async Task <DateTime> GetLastModifiedDateOfFile(string fileName)
    {
        try
        {
            _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + fileName);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = true;
            _ftpRequest.Method      = WebRequestMethods.Ftp.GetDateTimestamp;
            _ftpResponse            = (FtpWebResponse)await _ftpRequest.GetResponseAsync();
        }
        finally
        {
            _ftpStream?.Close();
            _ftpResponse?.Close();
            _ftpRequest = null;
        }

        if (_ftpResponse == null)
        {
            return(DateTime.MinValue);
        }

        return(_ftpResponse.LastModified);
    }
示例#12
0
 public async Task DownloadFileAsync(string ftpFilePath)
 {
     try
     {
         _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + ftpFilePath);
         _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
         _ftpRequest.UseBinary   = true;
         _ftpRequest.UsePassive  = true;
         _ftpRequest.KeepAlive   = true;
         _ftpRequest.Method      = WebRequestMethods.Ftp.DownloadFile;
         using (_ftpResponse = (FtpWebResponse)await _ftpRequest.GetResponseAsync())
         {
             using (_ftpStream = _ftpResponse.GetResponseStream())
             {
                 FileBytes = await ReadBytesAsync(_ftpResponse.GetResponseStream());
             }
         }
     }
     finally
     {
         _ftpStream?.Close();
         _ftpResponse?.Close();
         _ftpRequest = null;
     }
 }
        /// <summary>
        /// 判断ftp上的文件目录是否存在
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public bool RemoteFtpDirExists(string path)
        {
            path = _ftpconstr + path;
            FtpWebRequest reqFtp = (FtpWebRequest)WebRequest.Create(new Uri(path));

            reqFtp.UseBinary   = true;
            reqFtp.Credentials = new NetworkCredential(_ftpusername, _ftppassword);
            reqFtp.Method      = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse resFtp = null;

            try
            {
                resFtp = (FtpWebResponse)reqFtp.GetResponse();
                FtpStatusCode code = resFtp.StatusCode;
                Console.WriteLine(code);
                return(true);
            }
            catch (Exception exception)
            {
                Console.WriteLine("因{0},无法检测是否存在", exception.Message);
                return(false);
            }
            finally
            {
                resFtp?.Close();
            }
        }
示例#14
0
        private List <string> LoadList(bool details = false)
        {
            this.objLog.GravarLog(Log.TypeMessage.Message, "Trying connect to FTP server {" + this.sCurrentServerFTP + "}");

            List <string>  files          = new List <string>();
            FtpWebRequest  request        = null;
            FtpWebResponse response       = null;
            Stream         responseStream = null;

            try
            {
                request = (FtpWebRequest)WebRequest.Create(this.sCurrentServerFTP);

                request.Credentials = new NetworkCredential(this.sFTP_User, this.sFTP_Pass);
                request.UsePassive  = false;
                request.UseBinary   = true;
                request.KeepAlive   = false;

                request.Method = details ? WebRequestMethods.Ftp.ListDirectoryDetails : WebRequestMethods.Ftp.ListDirectory;

                using (response = (FtpWebResponse)request.GetResponse())
                {
                    responseStream = response.GetResponseStream();
                    using (StreamReader reader = new StreamReader(responseStream))
                    {
                        this.objLog.GravarLog(Log.TypeMessage.Message, "Getting list of files.");
                        files = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList <string>();
                    }
                }
            }
            catch (Exception ex)
            {
                this.objLog.GravarLog(Log.TypeMessage.Error, "Couldn't communicate for the FTP server " + this.sCurrentServerFTP + " (" + ex.Message + ") | " + ex.StackTrace);

                if (this.sCurrentServerFTP == this.sFTP_A)
                {
                    this.sCurrentServerFTP = this.sFTP_B;
                }
                else if (this.sCurrentServerFTP == this.sFTP_B)
                {
                    this.sCurrentServerFTP = this.sFTP_A;
                }

                bool changed = this.bCurrentServerChanged;
                this.bCurrentServerChanged = true;

                if (!changed)//if not changed before, try get again
                {
                    return(this.LoadList());
                }
            }
            finally
            {
                responseStream?.Close();
                response?.Close();
            }

            return(files);
        }
示例#15
0
        public void Close()
        {
            _ftpStream?.Close();
            _ftpRep?.Close();

            _ftpStream = null;
            _ftpRep    = null;
        }
示例#16
0
        private bool CopyFile(string psFile, string psDestination, bool pbShowLog)
        {
            bool           ret            = false;
            FtpWebRequest  request        = null;
            FtpWebResponse response       = null;
            Stream         responseStream = null;
            FileStream     newFile        = null;

            try
            {
                if (pbShowLog)
                {
                    this.objLog.GravarLog(Log.TypeMessage.Message, "Transferring File \"" + psFile + "\"");
                }

                request             = (FtpWebRequest)WebRequest.Create(this.sCurrentServerFTP + "/" + psFile);
                request.Credentials = new NetworkCredential(this.sFTP_User, this.sFTP_Pass);
                request.UsePassive  = false;
                request.UseBinary   = true;
                request.KeepAlive   = false;
                request.Method      = WebRequestMethods.Ftp.DownloadFile;

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

                byte[] buffer = new byte[8192];

                newFile = new FileStream(psDestination + @"\" + psFile, FileMode.Create);

                int readCount = responseStream.Read(buffer, 0, buffer.Length);

                while (readCount > 0)
                {
                    newFile.Write(buffer, 0, readCount);
                    readCount = responseStream.Read(buffer, 0, buffer.Length);
                }

                if (pbShowLog)
                {
                    this.objLog.GravarLog(Log.TypeMessage.Success, "Transferred File \"" + psFile + "\".");
                }

                ret = true;
            }
            catch (Exception ex)
            {
                this.objLog.GravarLog(Log.TypeMessage.Error, ex.Message + " | " + ex.StackTrace);
            }
            finally
            {
                newFile?.Close();
                responseStream?.Close();
                response?.Close();
            }

            return(ret);
        }
示例#17
0
    /* List Directory Contents in Detail (Name, Size, Created, etc.) */
    public async Task <List <FileProperty> > DirectoryListDetails(string directory)
    {
        var filePropertyList = new List <FileProperty>();

        try
        {
            _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + directory);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = true;
            _ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectoryDetails;
            using (_ftpResponse = (FtpWebResponse)await _ftpRequest.GetResponseAsync())
            {
                using (_ftpStream = _ftpResponse.GetResponseStream())
                {
                    if (_ftpStream != null)
                    {
                        _streamReader = new StreamReader(_ftpStream);
                    }
                    string line;
                    while ((line = _streamReader.ReadLine()) != null)
                    {
                        var fileListArr = line.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                        if (fileListArr.Count() >= 4)
                        {
                            FileProperty fileProperty = new FileProperty()
                            {
                                ModifiedDate = fileListArr[0] != null?DateTime.ParseExact(Convert.ToString(fileListArr[0]), "MM-dd-yy", null) : DateTime.MinValue,
                                                   FileName = fileListArr[3] != null?Convert.ToString(fileListArr[3]) : string.Empty,
                                                                  FileSize = fileListArr[2] != null && fileListArr[2] != "<DIR>" ? long.Parse(fileListArr[2]) : 0
                            };

                            filePropertyList.Add(fileProperty);
                        }
                    }
                }
            }
        }
        finally
        {
            _streamReader?.Close();
            _ftpStream?.Close();
            _ftpResponse?.Close();
            _ftpRequest = null;
        }

        if (filePropertyList.Any())
        {
            filePropertyList = filePropertyList.OrderByDescending(x => x.ModifiedDate).ToList();
        }

        return(filePropertyList);
    }
        /// <summary>
        /// 从ftp服务器下载文件的功能
        /// </summary>
        /// <param name="ftpFilepath">ftp下载的地址,相对路径</param>
        /// <param name="filePath">存放到本地的目录路径</param>
        /// <param name="fileName">保存的文件名称</param>
        /// <returns></returns>
        public bool Download(string ftpFilepath, string filePath, string fileName)
        {
            FtpWebRequest  reqFtp       = null;
            FtpWebResponse response     = null;
            Stream         ftpStream    = null;
            FileStream     outputStream = null;

            try
            {
                string onlyFileName = Path.GetFileName(fileName);
                string newFileName  = filePath + "\\" + onlyFileName;
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }
                ftpFilepath = ftpFilepath.Replace("\\", "/");
                var url = _ftpconstr + ftpFilepath;
                reqFtp             = (FtpWebRequest)WebRequest.Create(new Uri(url));
                reqFtp.UseBinary   = true;
                reqFtp.Credentials = new NetworkCredential(_ftpusername, _ftppassword);
                response           = (FtpWebResponse)reqFtp.GetResponse();
                ftpStream          = response.GetResponseStream();
                if (ftpStream == null)
                {
                    Console.WriteLine("数据流读取失败");
                    return(false);
                }
                var bufferSize = 2048;
                var buffer     = new byte[bufferSize];
                var readCount  = ftpStream.Read(buffer, 0, bufferSize);
                outputStream = new FileStream(newFileName, FileMode.Create);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                response.Close();
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("因{0},无法下载", ex.Message);
                return(false);
            }
            finally
            {
                reqFtp?.Abort();
                response?.Close();
                ftpStream?.Close();
                outputStream?.Close();
            }
        }
示例#19
0
            public bool IsDirectoryAlreadyPresentStandardFtp(IActivityIOPath path)
            {
                FtpWebResponse response = null;
                bool           isAlive;

                try
                {
                    var request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(path.Path));
                    request.Method    = WebRequestMethods.Ftp.ListDirectory;
                    request.UseBinary = true;
                    request.KeepAlive = false;
                    request.EnableSsl = EnableSsl(path);

                    if (path.Username != string.Empty)
                    {
                        request.Credentials = new NetworkCredential(path.Username, path.Password);
                    }

                    if (path.IsNotCertVerifiable)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                    }

                    using (response = (FtpWebResponse)request.GetResponse())
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (StreamReader reader = new StreamReader(responseStream))
                                {
                                    Dev2Logger.Info("FTP directory containing files " + reader.ReadToEnd() + " found at " + path.Path, GlobalConstants.WarewolfInfo);
                                }
                            }
                        }
                    }
                    isAlive = true;
                }
                catch (WebException wex)
                {
                    Dev2Logger.Error(this, wex, GlobalConstants.WarewolfError);
                    isAlive = false;
                }
                catch (Exception ex)
                {
                    Dev2Logger.Error(this, ex, GlobalConstants.WarewolfError);
                    throw;
                }
                finally
                {
                    response?.Close();
                }
                return(isAlive);
            }
示例#20
0
        // Use this method like this:
        //
        // Task<bool> downloadFilesTask = ftpDownloader.RetrieveFilesAsync(username, password);
        // DoSomeOtherStuff(); like telling the user that the app is downloading
        // bool success = await downloadFilesTask;
        //
        // if(success)...
        //
        public async Task <bool> RetrieveFilesAsync(string serverAdress, string userName, string password)
        {
            bool           isSuccessful    = false;
            FtpWebResponse response        = null;
            Stream         responseStream  = null;
            StreamReader   directoryReader = null;

            try {
                string        requestUrl = "ftp://" + serverAdress + "/%2F/SUGAR-CrossPlatform/SUGAR-CrossPlatform";
                FtpWebRequest request    = (FtpWebRequest)WebRequest.Create(requestUrl);
                request.Credentials = new NetworkCredential(userName, password);
                request.Method      = WebRequestMethods.Ftp.ListDirectory;
                request.KeepAlive   = false;
                request.UseBinary   = true;
                request.UsePassive  = true;

                response        = (FtpWebResponse)request.GetResponse();
                responseStream  = response.GetResponseStream();
                directoryReader = new StreamReader(responseStream);

                List <string> fileNames = new List <string>();
                directoryReader.ReadLine();                 // skip ".." directory
                string line = directoryReader.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    fileNames.Add(line);
                    line = directoryReader.ReadLine();
                }

                foreach (string fileName in fileNames)
                {
                    WebClient ftpClient = new WebClient();
                    ftpClient.Credentials = new NetworkCredential(userName, password);
                    string remotePath = "ftp://ftp.strato.com/%2F/SUGAR-CrossPlatform/" + fileName;
                    string localPath  = Path.Combine(GetFolderPath(), fileName);
                    if (!File.Exists(localPath))
                    {
                        await ftpClient.DownloadFileTaskAsync(remotePath, localPath);
                    }
                }
                isSuccessful = true;
            } catch (Exception e) {
                e.ToString();
                isSuccessful = false;
            } finally {
                directoryReader?.Close();
                responseStream?.Close();
                response?.Close();
            }

            return(isSuccessful);
        }
示例#21
0
    /* Get the Size of a File */
    public async Task <string> GetFileSize(string fileName)
    {
        try
        {
            _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + fileName);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = true;
            _ftpRequest.Method      = WebRequestMethods.Ftp.GetFileSize;
            using (_ftpResponse = (FtpWebResponse)await _ftpRequest.GetResponseAsync())
            {
                using (_ftpStream = _ftpResponse.GetResponseStream())
                {
                    if (_ftpStream != null)
                    {
                        var    ftpReader = new StreamReader(_ftpStream);
                        string fileInfo  = null;
                        while (ftpReader.Peek() != -1)
                        {
                            fileInfo = ftpReader.ReadToEnd();
                        }
                        ftpReader.Close();
                        _ftpStream?.Close();
                        _ftpResponse?.Close();
                        _ftpRequest = null;
                        return(fileInfo);
                    }
                }
            }
        }
        finally
        {
            _ftpResponse?.Close();
            _ftpRequest = null;
        }

        return("");
    }
示例#22
0
        string ExtendedDirListStandardFtp(string path, string user, string pass, bool ssl, bool isNotCertVerifiable)
        {
            FtpWebResponse resp   = null;
            string         result = null;

            try
            {
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(path));

                if (user != string.Empty)
                {
                    req.Credentials = new NetworkCredential(user, pass);
                }

                req.Method    = WebRequestMethods.Ftp.ListDirectoryDetails;
                req.KeepAlive = false;
                req.EnableSsl = ssl;

                if (isNotCertVerifiable)
                {
                    ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                }

                using (resp = (FtpWebResponse)req.GetResponse())
                {
                    using (Stream stream = resp.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            using (var reader = new StreamReader(stream, Encoding.UTF8))
                            {
                                result = reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Dev2Logger.Error(this, ex);
                throw;
            }
            finally
            {
                resp?.Close();
            }
            return(result);
        }
示例#23
0
    public async Task UploadFileAsync(string remoteFile, Stream fs)
    {
        try
        {
            var remoteFilePathResult = PrepareRemoteFilePath(Os.Linux, _host, remoteFile);

            if (remoteFilePathResult.IsFailure)
            {
                return;
            }

            _ftpRequest             = (FtpWebRequest)WebRequest.Create(remoteFilePathResult.Value);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.Method      = WebRequestMethods.Ftp.UploadFile;
            _ftpRequest.UseBinary   = true;
            _ftpRequest.KeepAlive   = true;

            _ftpRequest.ContentLength = fs.Length;
            var buffer     = new byte[4097];
            var totalBytes = (int)fs.Length;
            var rs         = _ftpRequest.GetRequestStream();
            while (totalBytes > 0)
            {
                var bytes = fs.Read(buffer, 0, buffer.Length);
                rs.Write(buffer, 0, bytes);
                totalBytes = totalBytes - bytes;
            }

            //fs.Flush();
            fs.Close();
            rs.Close();
            using (_ftpResponse = (FtpWebResponse)await _ftpRequest.GetResponseAsync())
            {
                var value = _ftpResponse.StatusDescription;
            }
        }
        catch (Exception e)
        {
            // log error
            throw;
        }
        finally
        {
            _ftpResponse?.Close();
            _ftpRequest = null;
        }
    }
示例#24
0
        /// <summary>
        /// 发送FTP请求
        /// </summary>
        /// <param name="method">操作方法</param>
        /// <param name="ftpFolder">远程路径(默认为当前路径)</param>
        /// <param name="KeepAlive">是否保持长连接(批量上传时请传入True)</param>
        /// <param name="preRequest">请求之前的处理</param>
        /// <param name="handleRequest">处理请求流的方法(无须释放请求流)</param>
        /// <param name="handleResponse">处理响应的方法(无须释放响应流)</param>
        /// <returns></returns>
        private string DoRequest(string method, string ftpFolder   = null, bool KeepAlive = false,
                                 Action <FtpWebRequest> preRequest = null, Action <Stream> handleRequest = null,
                                 Action <FtpWebResponse, Stream, StreamReader> handleResponse = null)
        {
            FtpWebResponse response = null;
            Stream         reqStream = null, rspStram = null;

            try
            {
                var request = CreateRequest(method, ftpFolder, KeepAlive);

                //添加额外的请求参数
                preRequest?.Invoke(request);

                response = (FtpWebResponse)request.GetResponse();

                //处理请求流,写入数据
                if (handleRequest != null)
                {
                    reqStream = request.GetRequestStream();
                    handleRequest.Invoke(reqStream);
                }

                rspStram = response.GetResponseStream();

                if (handleResponse != null)
                {
                    using (var reader = new StreamReader(rspStram, Encoding.UTF8))
                    {
                        //执行具体的操作
                        handleResponse(response, rspStram, reader);
                    }
                }

                return(string.Empty);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
            finally
            {
                reqStream?.Close();
                rspStram?.Close();
                response?.Close();
            }
        }
示例#25
0
        bool DeleteUsingStandardFtp(IList <IActivityIOPath> src)
        {
            FtpWebResponse response = null;


            foreach (var activityIOPath in src)
            {
                try
                {
                    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(activityIOPath.Path));

                    request.Method = PathIs(activityIOPath) == enPathType.Directory ? WebRequestMethods.Ftp.RemoveDirectory : WebRequestMethods.Ftp.DeleteFile;

                    request.UseBinary = true;
                    request.KeepAlive = false;
                    request.EnableSsl = EnableSsl(activityIOPath);

                    if (activityIOPath.IsNotCertVerifiable)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                    }

                    if (activityIOPath.Username != string.Empty)
                    {
                        request.Credentials = new NetworkCredential(activityIOPath.Username, activityIOPath.Password);
                    }

                    using (response = (FtpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode != FtpStatusCode.FileActionOK)
                        {
                            throw new Exception(@"Fail");
                        }
                    }
                }
                catch (Exception exception)
                {
                    throw new Exception(string.Format(ErrorResource.CouldNotDelete, activityIOPath.Path), exception);
                }
                finally
                {
                    response?.Close();
                }
            }
            return(true);
        }
示例#26
0
 public async Task DeleteFile(string deleteFile)
 {
     try
     {
         _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + deleteFile);
         _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
         _ftpRequest.UseBinary   = true;
         _ftpRequest.UsePassive  = true;
         _ftpRequest.KeepAlive   = true;
         _ftpRequest.Method      = WebRequestMethods.Ftp.DeleteFile;
         _ftpResponse            = (FtpWebResponse)await _ftpRequest.GetResponseAsync();
     }
     finally
     {
         _ftpResponse?.Close();
         _ftpRequest = null;
     }
 }
示例#27
0
 public async Task RenameFile(string currentFileNameAndPath, string newFileName)
 {
     try
     {
         _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host + currentFileNameAndPath);
         _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
         _ftpRequest.UseBinary   = true;
         _ftpRequest.UsePassive  = true;
         _ftpRequest.KeepAlive   = true;
         _ftpRequest.Method      = WebRequestMethods.Ftp.Rename;
         _ftpRequest.RenameTo    = newFileName;
         _ftpResponse            = (FtpWebResponse)await _ftpRequest.GetResponseAsync();
     }
     finally
     {
         _ftpResponse?.Close();
         _ftpRequest = null;
     }
 }
示例#28
0
        private void _coreCreateDirectory(string path, int responseTimeOut)
        {
            var request     = CreateWebRequest(path, WebRequestMethods.Ftp.MakeDirectory);
            var asyncResult = request.BeginGetResponse(null, null);

            if (asyncResult.AsyncWaitHandle.WaitOne(responseTimeOut, false))
            {
                FtpWebResponse response = null;
                try
                {
                    response = (FtpWebResponse)request.EndGetResponse(asyncResult);
                }
                finally
                { response?.Close(); }
            }
            else
            {
                request.Abort();
                throw new WebException(string.Empty, WebExceptionStatus.Timeout);
            }
        }
示例#29
0
            public bool CreateDirectoryStandardFtp(IActivityIOPath dst)
            {
                FtpWebResponse response = null;

                try
                {
                    var request = (FtpWebRequest)WebRequest.Create(ConvertSslToPlain(dst.Path));
                    request.Method    = WebRequestMethods.Ftp.MakeDirectory;
                    request.UseBinary = true;
                    request.KeepAlive = false;
                    request.EnableSsl = EnableSsl(dst);
                    if (dst.Username != string.Empty)
                    {
                        request.Credentials = new NetworkCredential(dst.Username, dst.Password);
                    }

                    if (dst.IsNotCertVerifiable)
                    {
                        ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
                    }
                    using (response = (FtpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode != FtpStatusCode.PathnameCreated)
                        {
                            throw new Exception(@"Fail");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Dev2Logger.Error(this, ex, GlobalConstants.WarewolfError);
                    // throw
                    return(false);
                }
                finally
                {
                    response?.Close();
                }
                return(true);
            }
示例#30
0
        private void _coreDeleteFile(string path, int responseTimeOut)
        {
            var request     = CreateWebRequest(path, WebRequestMethods.Ftp.DeleteFile);
            var asyncResult = request.BeginGetResponse(null, null);

            if (asyncResult.AsyncWaitHandle.WaitOne(responseTimeOut, false))
            {
                FtpWebResponse response = null;
                try
                {
                    response = (FtpWebResponse)request.EndGetResponse(asyncResult);
                }
                catch (WebException)
                { throw new FileNotFoundException(nameof(path)); }
                finally
                { response?.Close(); }
            }
            else
            {
                request.Abort();
                throw new WebException(string.Empty, WebExceptionStatus.Timeout);
            }
        }
示例#31
0
        /// <summary>
        ///     Makes the directory.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool MakeDirectory(string address)
        {
            if (RemoteFtpDirExists(address))
            {
                return(true);
            }
            FtpWebResponse res = null;

            try
            {
                var req = (FtpWebRequest)WebRequest.Create(address);
                req.Method = WebRequestMethods.Ftp.MakeDirectory;
                res        = (FtpWebResponse)req.GetResponse();
                res.Close();
                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                res?.Close();
                throw e;
            }
        }
示例#32
0
    public async Task <bool> CheckConnectionAsync()
    {
        try
        {
            _ftpRequest             = (FtpWebRequest)WebRequest.Create(_host);
            _ftpRequest.Credentials = new NetworkCredential(_user, _pass);
            _ftpRequest.UseBinary   = true;
            _ftpRequest.UsePassive  = true;
            _ftpRequest.KeepAlive   = false;
            _ftpRequest.Method      = WebRequestMethods.Ftp.ListDirectory;
            _ftpResponse            = (FtpWebResponse)await _ftpRequest.GetResponseAsync();

            return(true);
        }
        catch (Exception)
        {
            return(false);
        }
        finally
        {
            _ftpResponse?.Close();
            _ftpRequest = null;
        }
    }
示例#33
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 "";
	}
示例#34
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;
	}
示例#35
0
        public bool DownloadFile(string fileName = "vh_update.txt")
        {
            int           i       = 1;
            bool          error   = false;
            FtpWebRequest request = connect(fileName);

            try {
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                i = 2;
                List <string> dir = new List <string>();
                i = 3;
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                i = 4;
                Stream stream = response.GetResponseStream();
                i = 5;
                StreamReader reader = new StreamReader(stream);
                i = 6;
                MemoryStream memStream = new MemoryStream();
                byte[]       buffer    = new byte[1024]; //downloads in chuncks
                while (true)
                {
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        memStream.Write(buffer, 0, bytesRead);
                    }
                }
                reader.Close();
                response.Close();
                if (!Directory.Exists(downloadDir))
                {
                    try {
                        Directory.CreateDirectory(downloadDir);
                    }
                    catch (Exception e) {
                        Console.WriteLine(String.Format("Cannot create directory: {0} because {1}", downloadDir, e.Message));
                        return(false);
                    }
                }
                if (File.Exists(downloadDir + fileName) && !error)
                {
                    try {
                        File.Delete(downloadDir + fileName);
                    }
                    catch (Exception e) {
                        Console.WriteLine(String.Format("Cannot delete file: {0} because", downloadDir + fileName, e.Message));
                        return(false);
                    }
                }
                try {
                    using (FileStream fs = File.Create(downloadDir + fileName)) {
                        memStream.Position = 0;
                        memStream.CopyTo(fs);
                        fs.Close();
                        memStream.Close();
                    }
                }
                catch (Exception e) {
                    Console.WriteLine(String.Format("Cannot download {0} to {1} because: ", host + fileName, downloadDir + fileName));
                    return(false);
                }
                return(true);
            }
            catch (Exception e) {
                Console.WriteLine(String.Format("[FtpDirList] Exception at {0}: {1}", i, e.Message));
            }
            return(true);
        }
示例#36
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;
    }
示例#37
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;
    }