using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WarcViewerBlazorWinForm.Backend.IO { internal static class StreamExtension { public static void SeekForwardStupid(this Stream stream, long bytes) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (bytes < 0) throw new ArgumentOutOfRangeException(nameof(bytes)); if (bytes == 0) return; if (stream.CanSeek) { var newPosition = stream.Position + bytes; if (newPosition < 0 || newPosition > stream.Length) throw new ArgumentOutOfRangeException(nameof(bytes), "Attempted to move the stream pointer beyond its limits."); stream.Seek(bytes, SeekOrigin.Current); } else { var buffer = new byte[4096]; var remainingBytes = bytes; while (remainingBytes > 0) { var bytesRead = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, remainingBytes)); // Reached the end of the stream if (bytesRead == 0) throw new EndOfStreamException("Attempted to move the stream pointer beyond its limits."); remainingBytes -= bytesRead; } } } public static long GetLengthStupid(this Stream stream, int readAndDiscardBufferSize = 4096) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { return stream.Length; } catch (NotSupportedException) { // Ignore if getting length is not supported } try { if (stream.Position != 0) throw new InvalidOperationException("The stream position must be 0 when getting length."); } catch (NotSupportedException) { // Ignore if getting position is not supported } var buf = new byte[readAndDiscardBufferSize]; var totalRead = 0; do { var read = stream.Read(buf, 0, readAndDiscardBufferSize); if (read == 0) break; totalRead += read; } while (true); return totalRead; } } }