Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Products
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. CWE-22: Preventing Path Traversal in ASP.NET Core File Handling

CWE-22: Preventing Path Traversal in ASP.NET Core File Handling

Date- May 31,2026 456
cwe 22 path traversal

Overview

CWE-22, also known as Path Traversal, is a security vulnerability that allows an attacker to access files and directories that are stored outside the intended directory. This can lead to unauthorized file access, data leakage, and potentially the execution of malicious code. This vulnerability typically arises from inadequate validation of user input that is used to construct file paths. Given the critical nature of file handling in web applications, addressing CWE-22 is essential for maintaining application security.

Path traversal exploits can occur when user input is directly concatenated with file paths without proper sanitization. For instance, an attacker may input a path that includes ../ sequences to traverse to parent directories. The consequences of such exploits can be severe, ranging from accessing sensitive configuration files to executing arbitrary code on the server. Therefore, it is imperative for developers to understand the mechanisms that can prevent these vulnerabilities and implement robust validation and sanitization techniques.

Real-world use cases of path traversal vulnerabilities are numerous, with notable incidents leading to data breaches and exploitation. For example, the 2019 incident involving a popular web application framework revealed how attackers could read sensitive files by manipulating file paths. By examining these cases, developers can learn the importance of secure coding practices and the implementation of defense mechanisms against path traversal vulnerabilities.

Prerequisites

  • ASP.NET Core Knowledge: Familiarity with basic ASP.NET Core concepts, including middleware, controllers, and dependency injection.
  • C# Programming Skills: Proficiency in C# to effectively implement and understand code examples.
  • File Handling Basics: Understanding of file I/O operations in .NET, including reading from and writing to files.
  • Security Fundamentals: Basic knowledge of web application security principles and common vulnerabilities.

Understanding Path Traversal Vulnerabilities

Path traversal vulnerabilities occur when an application allows users to control file paths without sufficient validation. This typically happens when user input is used to construct file paths directly. Attackers can exploit this by manipulating input to traverse directories, potentially accessing sensitive files. To mitigate these risks, developers must validate and sanitize user inputs rigorously.

For example, consider a file upload feature that allows users to specify a file name. If the application does not validate the file name properly, an attacker could input a filename like ../../../etc/passwd (in Unix-like systems), thereby accessing sensitive system files. This illustrates the critical need for secure file handling practices in web applications.

public IActionResult DownloadFile(string fileName) {
    // Validate the file name
    if (string.IsNullOrWhiteSpace(fileName) || fileName.Contains("..")) {
        return BadRequest("Invalid file name.");
    }

    var filePath = Path.Combine(_storagePath, fileName);
    return PhysicalFile(filePath, "application/octet-stream");
}

In this example, we validate the fileName parameter to ensure it does not contain any .. sequences, which would indicate an attempt to traverse directories. The Path.Combine method is then used to create a safe file path.

Why Validation is Essential

Validation is essential because it acts as the first line of defense against unauthorized file access. By validating user inputs, developers can prevent attackers from manipulating file paths to access sensitive information. This not only protects the application but also builds trust with users, demonstrating that their data is handled securely.

Implementing Secure File Handling Practices

Implementing secure file handling practices involves validating and sanitizing inputs, restricting user access, and ensuring proper error handling. Developers should also adhere to the principle of least privilege, granting the minimum necessary permissions to files and directories. Additionally, using built-in methods for file path manipulation can help reduce the risk of path traversal vulnerabilities.

public IActionResult UploadFile(IFormFile file) {
    if (file.Length > 0) {
        var fileName = Path.GetFileName(file.FileName);
        var filePath = Path.Combine(_storagePath, fileName);

        using (var stream = new FileStream(filePath, FileMode.Create)) {
            file.CopyTo(stream);
        }
        return Ok();
    }
    return BadRequest("No file uploaded.");
}

This upload method first checks if the file is valid before proceeding. It uses Path.GetFileName to extract only the filename, ensuring that any path traversal attempts are neutralized. The file is then saved safely within the designated storage path.

Best Practices for Secure File Handling

Some best practices for secure file handling include:

  • Always validate and sanitize user inputs.
  • Use built-in methods for file path manipulation.
  • Implement strict access controls on file directories.
  • Limit file types and sizes for uploads.
  • Log file access attempts for monitoring and auditing.

Edge Cases & Gotchas

When implementing file handling features, developers must be aware of edge cases that could lead to vulnerabilities. For instance, allowing users to specify file extensions can be dangerous if not handled properly. Attackers may attempt to upload executable files disguised with different extensions.

public IActionResult UploadFile(IFormFile file) {
    if (file.Length > 0) {
        var fileName = Path.GetFileName(file.FileName);
        var fileExtension = Path.GetExtension(fileName);
        var allowedExtensions = new[] { ".jpg", ".png", ".pdf" };
        if (!allowedExtensions.Contains(fileExtension)) {
            return BadRequest("Invalid file type.");
        }
        var filePath = Path.Combine(_storagePath, fileName);
        using (var stream = new FileStream(filePath, FileMode.Create)) {
            file.CopyTo(stream);
        }
        return Ok();
    }
    return BadRequest("No file uploaded.");
}

In this code, we check the file extension against a list of allowed extensions before proceeding with the upload. This helps prevent the upload of potentially harmful files that could lead to security breaches.

Performance & Best Practices

When dealing with file handling in ASP.NET Core, performance considerations are crucial, especially when processing large files or handling a high volume of requests. To enhance performance while maintaining security, consider the following tips:

  • Use asynchronous file I/O operations to avoid blocking threads.
  • Implement caching for frequently accessed files.
  • Minimize memory usage by streaming large files instead of loading them entirely into memory.
  • Profile your application’s file handling operations to identify bottlenecks.
public async Task UploadFileAsync(IFormFile file) {
    if (file.Length > 0) {
        var fileName = Path.GetFileName(file.FileName);
        var filePath = Path.Combine(_storagePath, fileName);
        using (var stream = new FileStream(filePath, FileMode.Create)) {
            await file.CopyToAsync(stream);
        }
        return Ok();
    }
    return BadRequest("No file uploaded.");
}

This asynchronous upload method improves performance by allowing multiple requests to be processed concurrently without blocking the application. As a result, this leads to a more responsive application, especially under heavy load.

Real-World Scenario: Secure File Upload System

Let's consider a mini-project that demonstrates secure file handling in an ASP.NET Core application. This system will allow users to upload images securely while preventing path traversal vulnerabilities.

public class FileUploadController : Controller {
    private readonly string _storagePath = Path.Combine(Directory.GetCurrentDirectory(), "uploads");

    public FileUploadController() {
        if (!Directory.Exists(_storagePath)) {
            Directory.CreateDirectory(_storagePath);
        }
    }

    [HttpPost]
    public async Task UploadFileAsync(IFormFile file) {
        if (file.Length > 0) {
            var fileName = Path.GetFileName(file.FileName);
            var fileExtension = Path.GetExtension(fileName);
            var allowedExtensions = new[] { ".jpg", ".png" };
            if (!allowedExtensions.Contains(fileExtension)) {
                return BadRequest("Invalid file type.");
            }
            var filePath = Path.Combine(_storagePath, fileName);
            using (var stream = new FileStream(filePath, FileMode.Create)) {
                await file.CopyToAsync(stream);
            }
            return Ok();
        }
        return BadRequest("No file uploaded.");
    }
}

In this example, we define a FileUploadController that handles image uploads. We ensure that the upload directory exists and validate the file type before saving the file securely. This implementation addresses path traversal vulnerabilities while allowing users to upload files safely.

Conclusion

  • Path traversal vulnerabilities can lead to severe security breaches if not mitigated.
  • Validation and sanitization of user inputs are critical for secure file handling.
  • Utilizing built-in methods and following best practices can significantly reduce the risk of vulnerabilities.
  • Performance considerations are essential in file handling to maintain application responsiveness.
  • Real-world scenarios illustrate the practical application of secure coding principles.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

CWE-78: Preventing OS Command Injection in ASP.NET Core Applications
May 30, 2026
CWE-20: Mastering Input Validation in ASP.NET Core with Data Annotations and FluentValidation
Jun 03, 2026
Automating Let's Encrypt SSL Renewal in ASP.NET Core Using Certbot
May 26, 2026
Facebook Login Integration in ASP.NET Core with OAuth 2.0: A Comprehensive Guide
Apr 29, 2026
Previous in ASP.NET Core
CWE-78: Preventing OS Command Injection in ASP.NET Core Applicati…
Next in ASP.NET Core
CWE-798: Managing Secrets in ASP.NET Core with User Secrets and A…
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    CWE-269: Improper Privilege Management - Implementing the … 361 views
  • 2
    Send Email With HTML Template And PDF Using ASP.Net C# 17,203 views
  • 3
    Building Custom Bedrock Add-Ons with JavaScript: A Complet… 1,937 views
  • 4
    Error-An error occurred while processing your request in .… 11,964 views
  • 5
    Elasticsearch Integration in ASP.NET Core - Full-Text Sear… 243 views
  • 6
    Fix Gemini API Error 429: Quota Exceeded on Free Tier (Sys… 828 views
  • 7
    Integrating Google reCAPTCHA v3 in ASP.NET Core for Seamle… 613 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26683 views
  • Exception Handling Asp.Net Core 21720 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 21177 views
  • How to implement Paypal in Asp.Net Core 20127 views
  • Task Scheduler in Asp.Net core 18201 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1780
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Products
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor