---
title: "How to create Image file validator in production grade."  
description: "How to create Image file validator in production grade."  
author: "Ravi Vishwakarma"  
published: 2026-06-05  
updated: 2026-06-05  
canonical: https://www.mindstick.com/interview/34520/how-to-create-image-file-validator-in-production-grade  
category: "c#"  
tags: ["c#"]  
reading_time: 5 minutes  

---

# How to create Image file validator in production grade.

A production-grade image file validator should do much more than just check the file extension. The goal is to ensure the file is actually a valid image, meets your business requirements, and cannot be used for attacks.

## Validation Layers

### 1. Check File Size

Reject files that are too small or too large.

```cs
const long MaxFileSize = 5 * 1024 * 1024; // 5 MB

if (file.Length == 0 || file.Length > MaxFileSize)
{
    return "Invalid file size";
}
```

### 2. Validate Allowed Extensions

Only allow expected image formats.

```cs
var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".webp" };

var extension = Path.GetExtension(file.FileName).ToLowerInvariant();

if (!allowedExtensions.Contains(extension))
{
    return "Unsupported file type";
}
```

**Never rely only on extensions.**

A malicious file can be renamed:

```plaintext
virus.exe → image.jpg
```

### 3. Validate MIME Type

Check the content type sent by the client.

```cs
var allowedMimeTypes = new[]
{
    "image/jpeg",
    "image/png",
    "image/webp"
};

if (!allowedMimeTypes.Contains(file.ContentType))
{
    return "Invalid MIME type";
}
```

**Do not trust MIME type completely.** It can be spoofed.

### 4. Verify File Signature (Magic Numbers)

Inspect the first bytes of the file.

Example signatures:

| Format | Signature |
| --- | --- |
| JPEG | FF D8 FF |
| PNG | 89 50 4E 47 |
| WebP | RIFF....WEBP |

Example:

```cs
byte[] jpegSignature = { 0xFF, 0xD8, 0xFF };

using var stream = file.OpenReadStream();

byte[] buffer = new byte[3];
await stream.ReadAsync(buffer);

if (!buffer.SequenceEqual(jpegSignature))
{
    return "Invalid image";
}
```

This is one of the most important checks.

### 5. Attempt to Decode the Image

A valid image signature doesn't guarantee the image isn't corrupted.

Using `ImageSharp`:

```cs
using SixLabors.ImageSharp;

try
{
    using var image = await Image.LoadAsync(file.OpenReadStream());
}
catch
{
    return "Corrupted image";
}
```

If decoding fails, reject the upload.

### 6. Validate Dimensions

Prevent huge images:

```cs
using var image = await Image.LoadAsync(file.OpenReadStream());

if (image.Width > 5000 || image.Height > 5000)
{
    return "Image dimensions too large";
}
```

Example business rules:

```plaintext
Profile Photo:
Min: 200x200
Max: 3000x3000
```

### 7. Strip Metadata (Recommended)

Images can contain:

- GPS coordinates
- Device information
- Camera details

Remove metadata before storing.

```plaintext
image.Metadata.ExifProfile = null;
```

This improves privacy and security.

### 8. Generate Safe File Names

Never use:

```plaintext
file.FileName
```

Instead:

```plaintext
var fileName = $"{Guid.NewGuid()}.jpg";
```

Avoid:

```plaintext
../../../web.config
```

path traversal attacks.

### 9. Virus/Malware Scanning (Enterprise)

For high-security systems:

- ClamAV
- Microsoft Defender
- Cloud malware scanning services
- Scan before final storage.

### 10. Store Outside Web Root

Bad:

```plaintext
wwwroot/uploads
```

Better:

```plaintext
/storage/images
```

or

```plaintext
Azure Blob Storage
AWS S3
```

##

## Answers

### Answer by Ravi Vishwakarma

A production-grade image file validator should do much more than just check the file extension. The goal is to ensure the file is actually a valid image, meets your business requirements, and cannot be used for attacks.

## Validation Layers

### 1. Check File Size

Reject files that are too small or too large.

```cs
const long MaxFileSize = 5 * 1024 * 1024; // 5 MB

if (file.Length == 0 || file.Length > MaxFileSize)
{
    return "Invalid file size";
}
```

### 2. Validate Allowed Extensions

Only allow expected image formats.

```cs
var allowedExtensions = new[] { ".jpg", ".jpeg", ".png", ".webp" };

var extension = Path.GetExtension(file.FileName).ToLowerInvariant();

if (!allowedExtensions.Contains(extension))
{
    return "Unsupported file type";
}
```

**Never rely only on extensions.**

A malicious file can be renamed:

```plaintext
virus.exe → image.jpg
```

### 3. Validate MIME Type

Check the content type sent by the client.

```cs
var allowedMimeTypes = new[]
{
    "image/jpeg",
    "image/png",
    "image/webp"
};

if (!allowedMimeTypes.Contains(file.ContentType))
{
    return "Invalid MIME type";
}
```

**Do not trust MIME type completely.** It can be spoofed.

### 4. Verify File Signature (Magic Numbers)

Inspect the first bytes of the file.

Example signatures:

| Format | Signature |
| --- | --- |
| JPEG | FF D8 FF |
| PNG | 89 50 4E 47 |
| WebP | RIFF....WEBP |

Example:

```cs
byte[] jpegSignature = { 0xFF, 0xD8, 0xFF };

using var stream = file.OpenReadStream();

byte[] buffer = new byte[3];
await stream.ReadAsync(buffer);

if (!buffer.SequenceEqual(jpegSignature))
{
    return "Invalid image";
}
```

This is one of the most important checks.

### 5. Attempt to Decode the Image

A valid image signature doesn't guarantee the image isn't corrupted.

Using `ImageSharp`:

```cs
using SixLabors.ImageSharp;

try
{
    using var image = await Image.LoadAsync(file.OpenReadStream());
}
catch
{
    return "Corrupted image";
}
```

If decoding fails, reject the upload.

### 6. Validate Dimensions

Prevent huge images:

```cs
using var image = await Image.LoadAsync(file.OpenReadStream());

if (image.Width > 5000 || image.Height > 5000)
{
    return "Image dimensions too large";
}
```

Example business rules:

```plaintext
Profile Photo:
Min: 200x200
Max: 3000x3000
```

### 7. Strip Metadata (Recommended)

Images can contain:

- GPS coordinates
- Device information
- Camera details

Remove metadata before storing.

```plaintext
image.Metadata.ExifProfile = null;
```

This improves privacy and security.

### 8. Generate Safe File Names

Never use:

```plaintext
file.FileName
```

Instead:

```plaintext
var fileName = $"{Guid.NewGuid()}.jpg";
```

Avoid:

```plaintext
../../../web.config
```

path traversal attacks.

### 9. Virus/Malware Scanning (Enterprise)

For high-security systems:

- ClamAV
- Microsoft Defender
- Cloud malware scanning services
- Scan before final storage.

### 10. Store Outside Web Root

Bad:

```plaintext
wwwroot/uploads
```

Better:

```plaintext
/storage/images
```

or

```plaintext
Azure Blob Storage
AWS S3
```

##


---

Original Source: https://www.mindstick.com/interview/34520/how-to-create-image-file-validator-in-production-grade

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
