System.Net.Http.Headers.RangeHeaderValue

Represents the value of the Range header.

Summary

This class represents a Range header used in HTTP requests to specify a partial range of a resource to be downloaded. It allows clients to request only a portion of a file, which is useful for resuming interrupted downloads or for streaming content.

Constructors

Name Description
RangeHeaderValue(Int64) Initializes a new instance of the RangeHeaderValue class with a single byte range.
RangeHeaderValue(Int64, Int64) Initializes a new instance of the RangeHeaderValue class with a single byte range starting and ending at the specified positions.
RangeHeaderValue(Nullable<Int64>, Nullable<Int64>) Initializes a new instance of the RangeHeaderValue class with the specified start and end byte positions.

Properties

Name Type Description
Unit String Gets or sets the unit for the range header. The default is "bytes".
Ranges Collection<RangeItemHeaderValue> Gets a collection of byte range specifications.

Methods

Name Description
ToString() Returns a string representation of the RangeHeaderValue object.
Parse(String) Parses a string into a RangeHeaderValue instance.
TryParse(String, out RangeHeaderValue) Attempts to parse a string into a RangeHeaderValue instance and returns a value that indicates whether the parsing succeeded.

Example Usage

The following example demonstrates how to create and use a RangeHeaderValue object:

using System;
using System.Net.Http.Headers;

public class Example
{
    public static void Main(string[] args)
    {
        // Request the first 100 bytes of a resource
        var rangeHeader = new RangeHeaderValue(0, 99);
        Console.WriteLine($"Range header: {rangeHeader.ToString()}");
        // Output: Range header: bytes=0-99

        // Request from byte 500 onwards
        var rangeHeader2 = new RangeHeaderValue(500, null);
        Console.WriteLine($"Range header: {rangeHeader2.ToString()}");
        // Output: Range header: bytes=500-

        // Add another range (e.g., for multipart ranges)
        rangeHeader.Ranges.Add(new RangeItemHeaderValue(2000, 2999));
        Console.WriteLine($"Range header with multiple ranges: {rangeHeader.ToString()}");
        // Output: Range header with multiple ranges: bytes=0-99,2000-2999

        // Parsing a range header string
        string headerString = "bytes=100-500";
        RangeHeaderValue parsedRange;
        if (RangeHeaderValue.TryParse(headerString, out parsedRange))
        {
            Console.WriteLine($"Parsed range: {parsedRange.ToString()}");
            // Output: Parsed range: bytes=100-500
        }
    }
}