Exemplo n.º 1
0
        public static bool Read([NotNull] this WebResponse thisValue, [NotNull] IOSettings settings)
        {
            IIOOnRead    ioOnRead = settings as IIOOnRead ?? throw new ArgumentException("Argument must provide an OnRead implementation.", nameof(settings));
            Stream       stream   = null;
            StreamReader reader   = null;

            try
            {
                stream = GetStream(thisValue);
                if (stream == null)
                {
                    return(false);
                }
                reader = new StreamReader(stream, settings.Encoding, true);
                int    length;
                char[] chars = new char[settings.BufferSize];

                do
                {
                    length = reader.Read(chars);
                }while (length > 0 && ioOnRead.OnRead(chars, length));

                return(true);
            }
            catch (Exception ex) when(settings.OnError != null)
            {
                settings.OnError(ex);
                return(false);
            }
            finally
            {
                ObjectHelper.Dispose(ref reader);
                ObjectHelper.Dispose(ref stream);
            }
        }
Exemplo n.º 2
0
        public static Task <bool> ReadAsync([NotNull] this WebResponse thisValue, [NotNull] IOSettings settings, CancellationToken token = default(CancellationToken))
        {
            token.ThrowIfCancellationRequested();

            IIOOnRead    ioOnRead = settings as IIOOnRead ?? throw new ArgumentException("Argument must provide an OnRead implementation.", nameof(settings));
            Stream       stream   = null;
            StreamReader reader   = null;

            try
            {
                stream = GetStream(thisValue);
                token.ThrowIfCancellationRequested();
                if (stream == null)
                {
                    return(Task.FromResult(false));
                }
                reader = new StreamReader(stream, settings.Encoding, true);

                int    length;
                char[] chars = new char[settings.BufferSize];

                do
                {
                    length = reader.ReadAsync(chars).Execute();
                }while (!token.IsCancellationRequested && length > 0 && ioOnRead.OnRead(chars, length));

                token.ThrowIfCancellationRequested();
                return(Task.FromResult(true));
            }
            catch (Exception ex) when(settings.OnError != null)
            {
                settings.OnError(ex);
                return(Task.FromResult(false));
            }
            finally
            {
                ObjectHelper.Dispose(ref reader);
                ObjectHelper.Dispose(ref stream);
            }
        }