Skip to main content

Anti-Pattern: Hardcoded File Paths

Description

Embedding absolute file system paths (e.g., C:\Temp\, D:\WepFiles\) directly in the C# code.

Impact

  • Portability: The code fails immediately if run on a different machine (developer laptop), a different server (TEST vs PROD), or in a Container (Docker).
  • Brittleness: If the folder is deleted or permissions change, the app crashes.

Detection

Search for strings containing :\ or specific drive letters.

// ❌ BAD: Works only on the original developer's machine
var path = @"C:\Temp\my_file.txt";

Refactoring

  1. Configuration: Move the base path to web.config / appsettings.json.
  2. Server.MapPath: For web-relative paths, use HostingEnvironment.MapPath("~/App_Data/...").
  3. Temp Path: Use Path.GetTempPath().
// ✅ GOOD: Configurable and robust
var basePath = ConfigurationManager.AppSettings["ExportPath"]; // e.g., "D:\Exports" or "/var/data"
var path = Path.Combine(basePath, "my_file.txt");