Пример #1
0
        /// <summary>
        /// Copies up to the specified maximal number of bytes to the destination stream.
        /// </summary>
        /// <param name="bufferSize">Size of chunks read and written</param>
        /// <param name="destination">Destination stream</param>
        /// <param name="maxBytes">Maximal number of bytes to copy or <c>-1</c> to allow
        /// any number of bytes to be copied</param>
        /// <param name="source">Source stream</param>
        /// <exception cref="ArgumentException">Thrown if the source stream contains more than 
        /// <c>maxBytes</c> bytes</exception>
        public static void CopyUpTo(
            this Stream source, Stream destination, long maxBytes, int bufferSize = 1024)
        {
            ArgumentGuard.NotNull(source, nameof(source));
            ArgumentGuard.NotNull(destination, nameof(destination));
            ArgumentGuard.GreaterOrEqual(maxBytes, -1, nameof(maxBytes));

            if (maxBytes == -1)
            {
                maxBytes = long.MaxValue;
            }

            byte[] buffer = new byte[bufferSize];
            var totalRead = 0;
            int bytesRead;

            while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
            {
                totalRead += bytesRead;
                if (totalRead > maxBytes)
                {
                    throw new ArgumentException(
                        "source stream contains more than {0} bytes".Fmt(maxBytes));
                }

                destination.Write(buffer, 0, bytesRead);
            }
        }
        /// <summary>
        /// Split string by maximum length.
        /// </summary>
        /// <param name="str">The string to split.</param>
        /// <param name="n">The maximum number of characters in line. All lines will have that number of characters except (perhaps) the last.</param>
        /// <returns>An enumerable of strings, each represnting a line which is part of the original string.</returns>
        public static IEnumerable <string> Split(this string str, int n)
        {
            ArgumentGuard.NotEmpty(str, nameof(str));
            ArgumentGuard.GreaterOrEqual(n, 1, nameof(n));

            List <string> result = new List <string>();
            int           i      = 0;

            while (i < str.Length - n)
            {
                result.Add(str.Substring(i, n));
                i += n;
            }
            if (i < str.Length)
            {
                result.Add(str.Substring(i));
            }
            return(result.ToArray());
        }