Exemplo n.º 1
0
        /// <summary>
        /// Throws an exception if the server response is not one of the given acceptable codes
        /// </summary>
        /// <param name="response"></param>
        /// <param name="codes"></param>
        /// <returns></returns>
        private async Task BailIfResponseNotAsync(FTPResponse response, params FTPStatusCode[] codes)
        {
            if (codes.Any(x => x == response.FTPStatusCode))
            {
                return;
            }

            Logger?.LogDebug($"Bailing due to response codes being {response.FTPStatusCode}, which is not one of: [{string.Join(",", codes)}]");

            await LogOutAsync();

            throw new FTPException(response.ResponseMessage);
        }
        public async Task <FTPResponse> GetResponseAsync(CancellationToken token = default(CancellationToken))
        {
            Logger?.LogTrace("Getting Response");

            if (Encoding == null)
            {
                throw new ArgumentNullException(nameof(Encoding));
            }

            await receiveSemaphore.WaitAsync(token);

            try
            {
                token.ThrowIfCancellationRequested();

                var response = new FTPResponse();
                var data     = new List <string>();

                foreach (string line in ReadLines(token))
                {
                    token.ThrowIfCancellationRequested();
                    Logger?.LogDebug(line);
                    data.Add(line);

                    Match match;

                    if (!(match = Regex.Match(line, "^(?<statusCode>[0-9]{3}) (?<message>.*)$")).Success)
                    {
                        continue;
                    }
                    Logger?.LogTrace("Finished receiving message");
                    response.FtpStatusCode   = match.Groups["statusCode"].Value.ToStatusCode();
                    response.ResponseMessage = match.Groups["message"].Value;
                    break;
                }
                response.Data = data.ToArray();
                return(response);
            }
            finally
            {
                receiveSemaphore.Release();
            }
        }