Checking File Headers in C# Without Trusting the Extension

Editorial illustration.

Originally published 26 June 2023; rewritten and reviewed on 15 October 2026.

The simplest file upload check compares a filename extension with a short magic-byte pattern. In practice, that naive version breaks in two uncomfortable ways: a stream that ends earlier than the expected header (or returns partial reads from the network), and a ZIP archive pretending to be a different ZIP-based format. In an ASP.NET Core upload endpoint, I design the signature helper around those edge cases first before wiring it into a controller or minimal API handler.

Read only the prefix you need

Reading an entire IFormFile or request body into a byte[] just to inspect the first eight bytes is an easy way to invite memory pressure under concurrent uploads. A bounded prefix read keeps allocations tiny and predictable, even if a client sends a 50 MB payload.

If you are on .NET 7 or newer, Stream.ReadAtLeastAsync handles short-read loops for you, but if you maintain older .NET 6 or .NET Framework services—still common in enterprise and government projects—writing the explicit loop makes the behaviour unambiguous:

using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public static class FileSignature
{
    public static async Task<bool> HasPrefixAsync(
        Stream stream,
        ReadOnlyMemory<byte> expected,
        CancellationToken cancellationToken = default)
    {
        if (expected.IsEmpty)
        {
            return false;
        }

        byte[] header = new byte[expected.Length];
        int totalRead = 0;

        while (totalRead < header.Length)
        {
            int read = await stream.ReadAsync(
                header.AsMemory(totalRead),
                cancellationToken);

            if (read == 0)
            {
                return false; // Stream ended before the full signature could be read.
            }

            totalRead += read;
        }

        return header.AsSpan().SequenceEqual(expected.Span);
    }
}

A few details matter here when wiring this into an actual upload pipeline. First, never assume stream.ReadAsync fills the buffer in a single call—network-backed streams and MultipartReader sections frequently return fewer bytes than requested until the buffer is exhausted. Second, HasPrefixAsync advances the stream position. If you open the stream once via file.OpenReadStream() in ASP.NET Core and pass it straight to blob storage or an image processor afterwards, you must reset stream.Position = 0 when stream.CanSeek is true, or copy the bounded prefix before forwarding a non-seekable stream.

Map extensions to known signatures uniformly

Rather than scattering if/else chains across controllers, keep your expected byte prefixes in a single lookup table:

private static readonly IReadOnlyDictionary<string, byte[][]> KnownSignatures =
    new Dictionary<string, byte[][]>(StringComparer.OrdinalIgnoreCase)
    {
        [".png"] = [new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }],
        [".jpg"] = [new byte[] { 0xFF, 0xD8, 0xFF }],
        [".jpeg"] = [new byte[] { 0xFF, 0xD8, 0xFF }],
        [".pdf"] = [new byte[] { 0x25, 0x50, 0x44, 0x46, 0x2D }], // %PDF-
        [".zip"] = [new byte[] { 0x50, 0x4B, 0x03, 0x04 }],
    };

Notice that .jpg and .jpeg intentionally stop at FF D8 FF. Checking further bytes such as E0 or E1 rejects valid JPEGs that start with different APPn markers or EXIF/ICC segments. Checking an array of candidate prefixes per extension also lets you handle formats with multiple valid headers, such as UTF-8 vs UTF-16 BOMs or different container variants, without duplicating the stream logic.

Keep the result narrowly named

HasPrefixAsync describes exactly what was established: the stream began with those bytes. Naming the same method IsSafeFile or IsValidImage promises far more than a prefix check can deliver. A crafted payload can carry a valid %PDF- or PNG header and still contain malformed chunks, embedded JavaScript, or a decompression bomb.

The same trap applies to Office documents. .docx, .xlsx, .pptx, and .apk files all start with the ZIP local file header (50 4B 03 04). A prefix check alone cannot tell a .docx from an arbitrary .zip renamed to .docx. Treat the magic-byte check as a cheap gate that rejects obvious mismatches early; follow it with format-aware parsing (for example, ZipArchive entry inspection or an imaging library with strict pixel/dimension limits), store uploads outside the web root with generated filenames, and serve them with Content-Disposition: attachment or from a separate static domain.

Test the awkward inputs

Before trusting the helper in production, write unit tests for the edge cases that actually fail in HTTP handlers:

  • An empty stream (0 bytes) and a truncated header (3 bytes when checking an 8-byte PNG signature).
  • A one-byte mismatch at the very end of the prefix.
  • A custom Stream wrapper that returns 1 byte per ReadAsync call to prove your loop handles partial reads instead of silently failing on read < header.Length.
  • A seekable stream check verifying that your caller rewinds Position back to 0 before saving the uploaded file.

Pair those unit tests with integration tests for your upload endpoint’s max request body size, multipart limits, and disk permissions. A signature helper earns its keep by answering one narrow question reliably while leaving broader file validation explicit.