Table of Contents

Class ByteArrayExtensions

Namespace
Cuemon.Extensions.Net
Assembly
Cuemon.Extensions.Net.dll

Extension methods for the byte[].

public static class ByteArrayExtensions
Inheritance
ByteArrayExtensions

Examples

ByteArrayExtensions in the Net namespace URL-encodes byte arrays for safe HTTP transmission with support for partial encoding and custom character encodings. This example converts "hello world" to a UTF-8 byte array and calls UrlEncode to produce hello%20world, then demonstrates partial encoding of only the first five bytes (producing hello) and encoding with UTF-32 where each character is encoded as 4 bytes. Console output displays each encoded result, confirming that full encoding, partial ranges, and non-default encodings all produce correct percent-encoded output.

using System;
using System.Text;
using Cuemon.Extensions.Net;
using Cuemon.Text;

namespace MyApp.Net
{
    public class ByteArrayExtensionsExample
    {
        public void Demonstrate()
        {
            // Encode a byte array for safe URL transmission
            byte[] data = Encoding.UTF8.GetBytes("hello world");

            // URL-encode the entire byte array
            byte[] encoded = data.UrlEncode();
            Console.WriteLine(Encoding.UTF8.GetString(encoded));
            // Output: hello%20world

            // Encode only a portion starting at position 0 for 5 bytes
            byte[] partial = data.UrlEncode(position: 0, bytesToRead: 5);
            Console.WriteLine(Encoding.UTF8.GetString(partial));
            // Output: hello

            // Use a custom encoding (e.g., UTF-32)
            byte[] utf32Data = Encoding.UTF32.GetBytes("test data");
            byte[] utf32Encoded = utf32Data.UrlEncode(setup: o => o.Encoding = Encoding.UTF32);
            string result = Encoding.UTF32.GetString(utf32Encoded);
            Console.WriteLine(result);
            // Output: test%00%00%00%20%00%00%00data

}}
}

Methods

UrlEncode(byte[], int, int, Action<EncodingOptions>)

Converts the specified bytes into a URL-encoded array of bytes, starting at the specified position in the array and continuing for the specified number of bytesToRead.

public static byte[] UrlEncode(this byte[] bytes, int position = 0, int bytesToRead = -1, Action<EncodingOptions> setup = null)

Parameters

bytes byte[]

The byte[] to extend.

position int

The position in the byte array at which to begin encoding.

bytesToRead int

The number of bytes to encode.

setup Action<EncodingOptions>

The EncodingOptions which may be configured.

Returns

byte[]

An encoded byte[].

Exceptions

ArgumentNullException

bytes cannot be null.

ArgumentOutOfRangeException

position is lower than 0 - or - bytesToRead is lower than 0 - or - position is greater than or equal to the length of bytes - or - bytesToRead is greater than (the length of bytes minus position).