Example #1
0
        /// <summary>
        /// Calculates MD5 hash of required resource.
        ///
        /// Method has to run asynchronous.
        /// Resource can be any of type: http page, ftp file or local file.
        /// </summary>
        /// <param name="resource">Uri of resource</param>
        /// <returns>MD5 hash</returns>
        public static async Task <string> GetMD5Async(this Uri resource)
        {
            Stream stream;

            if (resource.Scheme == "ftp")
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(resource);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();

                stream = response.GetResponseStream();
            }
            else
            {
                stream = await new HttpClient().GetStreamAsync(resource);
            }
            MD5 md5 = new MD5CryptoServiceProvider();

            byte[]        res = md5.ComputeHash(stream);
            StringBuilder sb  = new StringBuilder();

            for (int i = 0; i < res.Length; i++)
            {
                sb.Append(res[i].ToString("X"));
            }
            return(sb.ToString());
        }
        public async Task <ServerResponse> DownloadDataFromFtpToLocalDisk(string sourceUrl, string protocol)
        {
            var serverResponse = ServerResponse.OK;

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(sourceUrl);
                request.Method      = WebRequestMethods.Ftp.DownloadFile;
                request.KeepAlive   = true;
                request.UsePassive  = true;
                request.UseBinary   = true; // use true for .zip file or false for a text file
                request.Credentials = new NetworkCredential(_appSettings.FtpNetworkCredential.UserName, _appSettings.FtpNetworkCredential.Password);

                WebResponse response = await request.GetResponseAsync();

                await _fileManager.GetDataFromResponseAndWriteLocalDisk(sourceUrl, response, protocol);

                return(serverResponse);
            }
            catch (Exception ex)
            {
                return(new ServerResponse()
                {
                    RespCode = 400, RespDesc = ex.Message
                });
            }
        }
Example #3
0
        public void UploadFile(FtpWebRequest request, Stream stream)
        {
            Stream requestStream = null;

            try
            {
                // Copy the contents of the file to the request stream.
                requestStream = request.GetRequestStream();
                byte[] fileContents = null;
                using (var br = new BinaryReader(stream))
                {
                    fileContents = br.ReadBytes((int)stream.Length);
                }
                requestStream.Write(fileContents, 0, fileContents.Length);

                request.GetResponseAsync().ContinueWith(t =>
                {
                    var response = t.Result as FtpWebResponse;
                    Sitecore.Diagnostics.Log.Info(string.Format("Sitecore FTP request sent to: {0}, Upload File Complete, status {1}", request.RequestUri.ToString(), response.StatusDescription), this);

                    requestStream.Close();
                    response.Close();
                });
            }
            catch (Exception ex)
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }

                Sitecore.Diagnostics.Log.Error(string.Format("Sitecore FtpClient Utility threw an error while uploading a file. Request: {0}", request.RequestUri.ToString()), ex, this);
                throw ex;
            }
        }
Example #4
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;
        }
    }
Example #5
0
 public async Task <bool> DownloadAsync(string sourceFile, string targetFile)
 {
     try
     {
         _ftp        = InitailizeFTP(sourceFile);
         _ftp.Method = WebRequestMethods.Ftp.DownloadFile;
         using (var ostrm = new FileStream(targetFile, FileMode.OpenOrCreate))
             using (var response = (FtpWebResponse)(await _ftp.GetResponseAsync()))
                 using (var strm = response.GetResponseStream())
                 {
                     var    bufferSize = 2048;
                     int    readCount;
                     byte[] buffer = new byte[bufferSize];
                     readCount = strm.Read(buffer, 0, bufferSize);
                     while (readCount > 0)
                     {
                         ostrm.Write(buffer, 0, readCount);
                         readCount = strm.Read(buffer, 0, bufferSize);
                     }
                 }
         return(true);
     }
     catch (Exception e)
     {
         throw new Exception(e.Message, e);
     }
 }
Example #6
0
        public async Task DownloadFileAsync(string fileName, string localPath)
        {
            var buffer = new byte[2048];

            FtpWebRequest request = CreateDownloadFtpRequest(RemoteUri + fileName, Port, User, Password);

            using (WebResponse response = await request.GetResponseAsync())
            {
                Stream responseStream = response.GetResponseStream();
                if (responseStream == null)
                {
                    throw new ArgumentNullException(nameof(responseStream));
                }

                using (var fileStream = new FileStream(localPath + fileName, FileMode.Create))
                {
                    while (true)
                    {
                        int bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length);

                        if (bytesRead == 0)
                        {
                            break;
                        }

                        await fileStream.WriteAsync(buffer, 0, bytesRead);
                    }
                }
            }
        }
Example #7
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);
    }
Example #8
0
        /// <summary>
        /// 异步下载文件
        /// </summary>
        /// <param name="ftpPath">ftp路径</param>
        /// <param name="ftpUserId">用户名</param>
        /// <param name="ftpPassword">密码</param>
        /// <param name="relativeFilePath">文件相对路径</param>
        public static async Task <MemoryStream> DownloadFileAsync(string ftpPath, string ftpUserId, string ftpPassword, string relativeFilePath)
        {
            try
            {
                FtpWebRequest request = null;

                LogTimeUtil log = new LogTimeUtil();
                request             = (FtpWebRequest)WebRequest.Create(new Uri(Path.Combine(ftpPath, relativeFilePath).Replace("\\", "/")));
                request.Credentials = new NetworkCredential(ftpUserId, ftpPassword);
                request.Method      = "RETR";
                FtpWebResponse response       = (FtpWebResponse)(await request.GetResponseAsync());
                Stream         responseStream = response.GetResponseStream();
                MemoryStream   stream         = new MemoryStream();
                byte[]         bArr           = new byte[1024 * 1024];
                int            size           = await responseStream.ReadAsync(bArr, 0, (int)bArr.Length);

                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = await responseStream.ReadAsync(bArr, 0, (int)bArr.Length);
                }
                stream.Seek(0, SeekOrigin.Begin);
                responseStream.Close();

                log.LogTime("FtpUtil.DownloadFileAsync 下载 filePath=" + relativeFilePath);
                return(stream);
            }
            catch (Exception ex)
            {
                LogUtil.Error("FtpUtil.DownloadFileAsync 异步下载文件 错误");
                throw ex;
            }
        }
Example #9
0
        /// <summary>
        /// Delete file
        /// </summary>
        /// <param name="url">The URI.</param>
        /// <returns>Returns <c>true</c> if operation is successfull; otherwise, <c>false</c>.</returns>
        public async Task <bool> DeleteFileAsync(Uri url)
        {
            bool result = true;

            try
            {
                FtpWebRequest request = this.CreateFtpWebRequest(url, WebRequestMethods.Ftp.DeleteFile);

                using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
                {
                    Stream data = response.GetResponseStream();
                }

                System.Diagnostics.Debug.WriteLine($"Deleted {url.AbsoluteUri}");
            }
            catch (OperationCanceledException)
            {
                System.Diagnostics.Debug.WriteLine("Delete file cancelled!");
                result = false;
            }
            catch (WebException e)
            {
                System.Diagnostics.Debug.WriteLine($"Failed to delete {url.AbsoluteUri}");
                System.Diagnostics.Debug.WriteLine(e);
                result = false;
                //throw;
            }

            return(result);
        }
Example #10
0
        public async Task <bool> AuthorizeFTPConnectionsAsync()
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Uri);

            request.Method      = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = credentials;
            request.UsePassive  = true;
            request.UseBinary   = true;
            request.KeepAlive   = false;


            try
            {
                WebResponse webResponse = await request.GetResponseAsync();

                //FtpWebResponse response = (FtpWebResponse)webResponse;
                return(true);
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Retrieve the object asynchronously.
        /// </summary>
        /// <param name="token">Cancellation token to cancel the request.</param>
        /// <returns>Crawl result.</returns>
        public async Task <CrawlResult> GetAsync(CancellationToken token = default)
        {
            CrawlResult ret = new CrawlResult();

            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(SourceUrl);
                request.Method      = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(Username, Password);
                FtpWebResponse response = (FtpWebResponse)(await request.GetResponseAsync().ConfigureAwait(false));

                Stream responseStream = response.GetResponseStream();
                await responseStream.CopyToAsync(ret.DataStream, _StreamBufferSize, token).ConfigureAwait(false);

                ret.ContentLength = responseStream.Length;
                response.Close();

                ret.Success = true;
            }
            catch (Exception e)
            {
                ret.Exception = e;
            }

            ret.Time.End = DateTime.UtcNow;
            return(ret);
        }
Example #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;
     }
 }
Example #13
0
        public async Task <bool> Exists(string fileName, DirectoryEnum directoryEnum = DirectoryEnum.Published)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(GetFilePath(fileName, directoryEnum));

            request.Credentials = Credentials;
            request.UseBinary   = true;
            request.KeepAlive   = true;
            request.Method      = WebRequestMethods.Ftp.GetFileSize;
            FtpWebResponse response = null;

            try
            {
                response = (FtpWebResponse)(await request.GetResponseAsync());
                return(true);
            }
            catch (WebException ex)
            {
                response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    return(false);
                }
            }
            return(false);
        }
Example #14
0
        public async Task DownLoadFileAsync(FtpTransferResult ftpResult,
                                            CancellationTokenSource cancelltionTokenSource)
        {
            byte[]        buffer  = new byte[BUFFER_LENGTH];
            FtpWebRequest request = FtpWebRequest.Create("ftp://" +
                                                         this.Ftp.Host + ":" + this.Ftp.Port + ftpResult.Info) as FtpWebRequest;

            request.Credentials      = new NetworkCredential(this.Ftp.UserName, this.Ftp.Password);
            request.Method           = WebRequestMethods.Ftp.DownloadFile;
            request.Timeout          = 10000;
            request.ReadWriteTimeout = 10000;
            using (var response = await request.GetResponseAsync() as FtpWebResponse)
                using (var stream = response.GetResponseStream())
                    using (var filestream = new FileStream(ftpResult.Target, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                    {
                        int readed = 0;
                        while ((readed = await stream.ReadAsync(buffer, 0, BUFFER_LENGTH)) > 0)
                        {
                            if (cancelltionTokenSource.IsCancellationRequested)
                            {
                                break;
                            }
                            await filestream.WriteAsync(buffer, 0, readed);

                            ftpResult.Position += readed;
                            ftpResult.Process   = (double)ftpResult.Position / ftpResult.TotalLength * 100;
                        }
                        await filestream.FlushAsync();
                    }
        }
Example #15
0
        public async Task <string[]> GetDirectoryContentsAsync(string relativePath)
        {
            string[] result = new string[] { "" };
            try
            {
                FtpWebRequest request = GetFTPRequest(relativePath, WebRequestMethods.Ftp.ListDirectoryDetails);
                using (var response = await request.GetResponseAsync())
                {
                    TextReader    reader = new StreamReader(response.GetResponseStream());
                    List <string> lines  = new List <string>();

                    bool   escape = false;
                    string line;

                    while (!escape)
                    {
                        line   = reader.ReadLine();
                        escape = line == null;

                        if (!escape)
                        {
                            lines.Add(line);
                        }
                    }
                    result = lines.ToArray();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                OnFailedLogon(ex.Message);
            }

            return(result);
        }
Example #16
0
        /// <summary>
        /// Verify whether the directory exists.
        /// </summary>
        private async Task <bool> VerifyDirectoryExistAsync(Uri url)
        {
            FtpWebRequest request = this.CreateFtpWebRequest(url, WebRequestMethods.Ftp.ListDirectory);

            try
            {
                using (FtpWebResponse response = await request.GetResponseAsync() as FtpWebResponse)
                {
                    // Messages
                    this.OnNewMessageArrived(new NewMessageEventArgs(response.BannerMessage));
                    this.OnNewMessageArrived(new NewMessageEventArgs(response.WelcomeMessage));
                    this.OnNewMessageArrived(new NewMessageEventArgs(response.StatusDescription));

                    //return response.StatusCode == FtpStatusCode.DataAlreadyOpen;
                    return(true);
                }
            }
            catch (System.Net.WebException webEx)
            {
                FtpWebResponse ftpResponse = webEx.Response as FtpWebResponse;

                if (ftpResponse.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    return(false);
                }

                throw;
            }
        }
 private static async Task <Stream> GetFtpFile(FtpWebRequest ftpRequest)
 {
     using (WebResponse ftpResponse = await ftpRequest.GetResponseAsync().ConfigureAwait(false))
     {
         return(ftpResponse.GetResponseStream());
     }
 }
Example #18
0
        public async Task <string> GetDirectory(string HostName, string UserName, string Password, int Port)
        {
            StringBuilder strBuilder = new StringBuilder();

            if (Port > 0)
            {
                HostName += HostName + ":" + Port + "/";
            }
            FtpWebRequest req = (FtpWebRequest)WebRequest.Create(HostName);

            req.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

            req.Credentials = new NetworkCredential(UserName, Password);
            req.EnableSsl   = false;

            FtpWebResponse resp = (FtpWebResponse)await req.GetResponseAsync();

            using (var respStream = resp.GetResponseStream()) {
                using (var reader = new StreamReader(respStream)) {
                    strBuilder.Append(reader.ReadToEnd());
                    strBuilder.Append(resp.WelcomeMessage);
                    strBuilder.Append($"Request returned status:  {resp.StatusDescription}");
                }
            }
            return(strBuilder.ToString());
        }
Example #19
0
        /// <summary>
        /// Request a RemoveDirectory action on the targeted Directory. The target must exists.
        /// </summary>
        /// <param name="cancelToken">The token to cancel the query</param>
        /// <param name="options">The query-specific options</param>
        /// <returns>A Task</returns>
        public async Task RemoveDirectory(CancellationToken cancelToken, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, WebRequestMethods.Ftp.RemoveDirectory);

            using (var response = (FtpWebResponse)await request.GetResponseAsync())
                cancelToken.ThrowIfCancellationRequested();
        }
Example #20
0
        /// <summary>
        /// Request a Download action on the targeted file.
        /// </summary>
        /// <param name="stream">The stream that will be written to</param>
        /// <param name="cancelToken">The token to cancel the query</param>
        /// <param name="progress">The progress monitor</param>
        /// <param name="options">The query-specific options</param>
        /// <returns>A Task</returns>
        public async Task Download(Stream stream, CancellationToken cancelToken, ProgressMonitorBase progress = null, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            options = options ?? Handler.Options;
            FtpWebResponse response = null;
            FtpWebRequest  request  = null;

            if (progress != null)
            {
                long size = -1;
                if (progress.AskForSize)
                {
                    try {
                        size = await GetFileSize(cancelToken);
                    } catch { }
                }
                progress.Progress = new FtpProgress(size);
                progress.OnInit();
            }
            if (cancelToken.IsCancellationRequested)
            {
                cancelToken.ThrowIfCancellationRequested();
            }
            request  = Handler.MakeRequest(cancelToken, options, Target, WebRequestMethods.Ftp.DownloadFile);
            response = (FtpWebResponse)await request.GetResponseAsync();

            cancelToken.ThrowIfCancellationRequested();
            byte[] buffer    = new byte[options.BufferSize];
            int    readCount = 0;

            try {
                using (var responseStream = response.GetResponseStream()) {
                    if (progress != null)
                    {
                        progress.Progress.StartRateTimer();
                    }
                    do
                    {
                        readCount = await responseStream.ReadAsync(buffer, 0, options.BufferSize, cancelToken);

                        await stream.WriteAsync(buffer, 0, readCount, cancelToken);

                        cancelToken.ThrowIfCancellationRequested();
                        if (progress != null)
                        {
                            progress.Progress.CurrentCount += readCount;
                            progress.Progress.AddToRate(readCount);
                            progress.Progressed();
                        }
                    } while (readCount > 0);
                }
            } finally {
                if (progress != null)
                {
                    progress.Progress.StopRateTimer();
                }
            }
        }
Example #21
0
        public override async Task Upload(string path, string name, byte[] buffer, bool allowCreateDirectory = true)
        {
            Exception exception         = null;
            bool      directoryNotExist = false;

            try
            {
                if (base.Config.Folder != "/")
                {
                    path = base.Config.Folder + path.TrimStart('/');
                }

                string url = string.Format("{0}://{1}:{2}/{3}/{4}"
                                           , base.Config.Protocol
                                           , base.Config.Server
                                           , base.Config.Port
                                           , path.Trim('/')
                                           , name
                                           );

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
                request.UseBinary     = true;
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.ContentLength = buffer.Length;
                request.Credentials   = new NetworkCredential(base.Config.Username, base.Config.Password);
                Stream requestStream = await request.GetRequestStreamAsync();

                await requestStream.WriteAsync(buffer, 0, buffer.Length);

                requestStream.Close();
                await request.GetResponseAsync();

                return;
            }
            catch (WebException ex)
            {
                exception = ex;
                FtpWebResponse response = ex.Response as FtpWebResponse;
                if (response != null)
                {
                    if (response.StatusCode == FtpStatusCode.ActionNotTakenFilenameNotAllowed)
                    {
                        // directory not exist
                        directoryNotExist = true;
                    }
                }
            }

            if (directoryNotExist && allowCreateDirectory)
            {
                await CreateDir(path);
                await Upload(path, name, buffer);
            }
            else
            {
                throw exception;
            }
        }
Example #22
0
        //都调用这个

        private async System.Threading.Tasks.Task <string[]> GetFileListAsync(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
        {
            string[]      downloadFiles;
            StringBuilder result = new StringBuilder();

            try
            {
                Connect(path);

                reqFTP.Method = WRMethods;

                WebResponse response = await reqFTP.GetResponseAsync();

                StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名

                string line = reader.ReadLine();

                while (line != null)
                {
                    result.Append(line);

                    result.Append("\n");

                    line = reader.ReadLine();
                }

                // to remove the trailing '\n'

                result.Remove(result.ToString().LastIndexOf('\n'), 1);

                reader.Close();

                response.Close();

                return(result.ToString().Split('\n'));
            }

            catch (Exception ex)
            {
                downloadFiles = null;

                return(downloadFiles);
            }
        }
Example #23
0
        public async Task <FtpWebResponse> GetRawResponseStream(FTPfileInfo file)
        {
            FtpWebRequest ftp = await GetRequest(_hostname + file.FullName);

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

            return((FtpWebResponse)await ftp.GetResponseAsync());
        }
Example #24
0
        /// <summary>
        /// Query the last modified time of the target.
        /// </summary>
        /// <param name="cancelToken">The token to cancel the query</param>
        /// <param name="options">The query-specific options</param>
        /// <returns>The last modified time of the targeted file</returns>
        public async Task <DateTime> GetDatestamp(CancellationToken cancelToken, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, WebRequestMethods.Ftp.GetDateTimestamp);

            using (var response = (FtpWebResponse)await request.GetResponseAsync()) {
                cancelToken.ThrowIfCancellationRequested();
                return(response.LastModified);
            }
        }
Example #25
0
        /// <summary>
        /// Query the Current directory.
        /// </summary>
        /// <param name="cancelToken">The token to cancel the query</param>
        /// <param name="options">The query-specific options</param>
        /// <returns>The working directory</returns>
        public async Task <string> PrintWorkingDirectory(CancellationToken cancelToken, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, WebRequestMethods.Ftp.PrintWorkingDirectory);

            using (var response = (FtpWebResponse)await request.GetResponseAsync()) {
                cancelToken.ThrowIfCancellationRequested();
                return(response.StatusDescription);
            }
        }
Example #26
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);
    }
Example #27
0
        /// <summary>
        /// Query the file size of the target.
        /// </summary>
        /// <param name="cancelToken">The token to cancel the query</param>
        /// <param name="options">The query-specific options</param>
        /// <returns>The size of the targeted file</returns>
        public async Task <long> GetFileSize(CancellationToken cancelToken, FtpOptions options = null)
        {
            cancelToken.ThrowIfCancellationRequested();
            FtpWebRequest request = Handler.MakeRequest(cancelToken, options, Target, WebRequestMethods.Ftp.GetFileSize);

            using (var response = (FtpWebResponse)await request.GetResponseAsync()) {
                cancelToken.ThrowIfCancellationRequested();
                using (var sizeStream = response.GetResponseStream())
                    return(response.ContentLength);
            }
        }
Example #28
0
 private static async Task <FtpWebResponse> GetResponseAsync([NotNull] FtpWebRequest request)
 {
     try {
         return((FtpWebResponse)await request.GetResponseAsync());
     } catch (WebException exc) {
         Console.WriteLine(exc);
         Debug.Assert(exc.Response != null, "exc.Response != null");
         exc.Response.Dispose();
         return(null);
     }
 }
Example #29
0
        /// <summary>
        /// Get all file names in a directory
        /// </summary>
        /// <returns>
        /// Array of file names as strings
        /// </returns>
        public async Task <string[]> DirectoryListAsync()
        {
            try
            {
                Log.Verbose("Request to get file list from directory {0}", RemoteDirectory);
                StringBuilder result     = new StringBuilder();
                FtpWebRequest ftpRequest = ConstructFtpRequest(null);
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

                using (WebResponse response = await ftpRequest.GetResponseAsync())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string line = reader.ReadLine();
                        while (line != null)
                        {
                            // We only care about log files in .txt extensions
                            if (line.EndsWith(".txt", true, CultureInfo.InvariantCulture))
                            {
                                result.Append(line);
                                result.Append(";");
                            }
                            line = reader.ReadLine();
                        }
                        if (!string.IsNullOrEmpty(result.ToString()))
                        {
                            result.Remove(result.ToString().LastIndexOf(';'), 1);
                            string[] fileList = result.ToString().Split(';');
                            Log.Information("Following files are available in {0} directory", RemoteDirectory);
                            foreach (string fileName in fileList)
                            {
                                Log.Information("File Name : {0}", fileName);
                            }
                            return(result.ToString().Split(';'));
                        }

                        Log.Information("No files are available in {0} directory", RemoteDirectory);
                        return(null);
                    }
                }
            }
            catch (Exception exception)
            {
                Log.Error(
                    "Error during directory list operation. " +
                    "Directory : {0} , Uri : {1}",
                    exception,
                    RemoteDirectory,
                    FtpUri);

                throw;
            }
        }
Example #30
0
        /// <summary>
        /// Upload file to ftp server
        /// </summary>
        /// <param name="ftpSite"></param>
        /// <param name="uploadFile"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public async Task UploadFileAsync(Uri ftpSite, string uploadFile, string username, string password)
        {
            int totalBytes = 0;

            Console.WriteLine("Uploading {uploadFile} to {ftpSite.AbsoluteUri}...");

            try
            {
                FileInfo fileInfo = new FileInfo(uploadFile);

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpSite);
                request.Method        = WebRequestMethods.Ftp.UploadFile;
                request.UseBinary     = true;
                request.ContentLength = fileInfo.Length;

                request.Credentials = new NetworkCredential(username, password);
                byte[] byteBuffer = new byte[4096];

                using (Stream requestStream = await request.GetRequestStreamAsync())
                {
                    using (FileStream fileStream = new FileStream(uploadFile, FileMode.Open, FileAccess.Read,
                                                                  FileShare.Read, 4096, useAsync: true))
                    {
                        int bytesRead = 0;
                        do
                        {
                            bytesRead = await fileStream.ReadAsync(byteBuffer, 0, byteBuffer.Length);

                            if (bytesRead > 0)
                            {
                                totalBytes += bytesRead;
                                Console.WriteLine("Uploaded {totalBytes} Bytes");

                                await requestStream.WriteAsync(byteBuffer, 0, bytesRead);
                            }
                        } while (bytesRead > 0);
                    }
                }

                using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
                {
                    Console.WriteLine(response.StatusDescription);
                }

                Console.WriteLine("Uploaded {uploadFile} to {ftpSite.AbsoluteUri}...");
            }
            catch (WebException e)
            {
                Console.WriteLine("Failed to upload {uploadFile} to {ftpSite.AbsoluteUri}.");
                Console.WriteLine(((FtpWebResponse)e.Response).StatusDescription);
                Console.WriteLine(e);
            }
        }
Example #31
0
        private static async Task<MemoryStream> DoAsync(FtpWebRequest request, MemoryStream requestBody)
        {
            if (requestBody != null)
            {
                Stream requestStream = await request.GetRequestStreamAsync();
                await requestBody.CopyToAsync(requestStream);
                requestStream.Close();
            }

            MemoryStream responseBody = new MemoryStream();
            FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync();
            await response.GetResponseStream().CopyToAsync(responseBody);
            response.Close();

            return responseBody;
        }