C# PathTooLongException
last modified April 20, 2025
This tutorial explains how to handle the PathTooLongException in C# when working with file paths that exceed system limits. The exception occurs when path names are too long for the file system.
The PathTooLongException class represents an exception thrown when a path or file name exceeds the maximum length defined by the system. In Windows, the maximum path length is typically 260 characters.
PathTooLongException
inherits from IOException
and is
part of the System.IO
namespace. It indicates that path-related
operations failed due to path length limitations.
Basic PathTooLongException Example
This example demonstrates how a PathTooLongException occurs when attempting to create a file with a path that exceeds system limits.
using System; using System.IO; class Program { static void Main() { try { string longPath = @"C:\" + new string('x', 300); File.Create(longPath); } catch (PathTooLongException ex) { Console.WriteLine("Error: " + ex.Message); Console.WriteLine("Path length exceeded system limits."); } } }
The code attempts to create a file with a path exceeding 300 characters. This triggers a PathTooLongException on most Windows systems. The example shows how to catch and handle this specific exception type.
The exception message provides details about the error. The catch block handles the exception gracefully by displaying an informative message. This pattern is essential for robust file system operations.
Checking Path Length Before Operations
This example shows how to proactively check path length before performing file operations to avoid PathTooLongException.
using System; using System.IO; class Program { static void Main() { string path = @"C:\temp\" + new string('a', 250); if (path.Length > 260) { Console.WriteLine("Path is too long. Maximum allowed is 260 characters."); Console.WriteLine("Current length: " + path.Length); return; } try { Directory.CreateDirectory(path); Console.WriteLine("Directory created successfully."); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); } } }
The code checks the path length before attempting directory creation. This preventive approach avoids exceptions by validating constraints first. The example uses a simple length check against the Windows limit.
While 260 characters is the traditional Windows limit, newer systems may support longer paths with proper configuration. The check provides basic protection against common cases.
Handling Long Paths with UNC Prefix
This example demonstrates using the UNC prefix to work with long paths on supported Windows systems.
using System; using System.IO; class Program { static void Main() { string longPath = @"\\?\" + @"C:\temp\" + new string('b', 300); try { Directory.CreateDirectory(longPath); Console.WriteLine("Long path directory created."); } catch (PathTooLongException ex) { Console.WriteLine("Still too long: " + ex.Message); } catch (Exception ex) { Console.WriteLine("Other error: " + ex.Message); } } }
The UNC prefix (\\?\) allows paths up to 32,767 characters on Windows. This example attempts to create a directory with a very long path. The prefix bypasses the traditional 260-character limit.
Note that not all Windows APIs support UNC paths. The application must be configured for long path support in the manifest or registry. This technique works best on newer Windows versions.
PathTooLongException with File Operations
This example shows how PathTooLongException can occur during various file operations like reading or writing files.
using System; using System.IO; class Program { static void Main() { string longFilePath = @"C:\" + new string('d', 250) + @"\file.txt"; try { string content = File.ReadAllText(longFilePath); Console.WriteLine("File read successfully."); } catch (PathTooLongException) { Console.WriteLine("Cannot read file - path too long."); } catch (DirectoryNotFoundException) { Console.WriteLine("Directory not found."); } catch (FileNotFoundException) { Console.WriteLine("File not found."); } } }
The example attempts to read a file with a long path. Multiple exception types are caught to handle different failure scenarios. PathTooLongException is caught specifically for path length issues.
This pattern demonstrates proper exception handling hierarchy. More specific exceptions should be caught before more general ones. The code provides appropriate feedback for each error case.
Working with Relative Paths
This example shows how relative paths can also trigger PathTooLongException when combined with the current directory path.
using System; using System.IO; class Program { static void Main() { string relativePath = new string('e', 300) + ".txt"; try { string fullPath = Path.GetFullPath(relativePath); Console.WriteLine("Full path: " + fullPath); if (fullPath.Length > 260) { throw new PathTooLongException( "Combined path exceeds maximum length"); } File.WriteAllText(relativePath, "Test content"); } catch (PathTooLongException ex) { Console.WriteLine("Path too long: " + ex.Message); } } }
The code demonstrates how relative paths combine with the current directory. The full path length is checked explicitly to prevent exceptions. This approach provides more control over path length validation.
The example shows manual exception throwing when business logic detects an invalid state. This technique can provide more context than automatic exceptions from framework methods.
Handling PathTooLongException in Recursive Methods
This example demonstrates handling PathTooLongException in recursive file system operations where paths might become too long.
using System; using System.IO; class Program { static void ProcessDirectory(string path, int depth) { try { foreach (var file in Directory.GetFiles(path)) { Console.WriteLine(file); } foreach (var dir in Directory.GetDirectories(path)) { ProcessDirectory(dir, depth + 1); } } catch (PathTooLongException) { Console.WriteLine($"Skipping long path at depth {depth}"); } catch (UnauthorizedAccessException) { Console.WriteLine($"Access denied at depth {depth}"); } } static void Main() { string startPath = @"C:\Program Files"; ProcessDirectory(startPath, 0); } }
The recursive directory processing method includes specific handling for PathTooLongException. This prevents the entire operation from failing when encountering one invalid path.
The example shows how to maintain operation continuity despite exceptions. Depth tracking helps diagnose where problems occur in the directory tree. This pattern is useful for robust file system scanners.
Custom Path Shortening Solution
This example implements a custom path shortening solution to avoid PathTooLongException while preserving functionality.
using System; using System.IO; class Program { static string GetShortenedPath(string basePath, string relativePath) { string fullPath = Path.Combine(basePath, relativePath); if (fullPath.Length = 260) { return fullPath; } // Custom shortening logic string[] parts = relativePath.Split(Path.DirectorySeparatorChar); string shortened = ""; foreach (string part in parts) { if (part.Length > 8) { shortened += part.Substring(0, 6) + "~" + Path.DirectorySeparatorChar; } else { shortened += part + Path.DirectorySeparatorChar; } } shortened = shortened.TrimEnd(Path.DirectorySeparatorChar); return Path.Combine(basePath, shortened); } static void Main() { string basePath = @"C:\temp"; string longRelative = new string('f', 50) + Path.DirectorySeparatorChar + new string('g', 50) + Path.DirectorySeparatorChar + "file.txt"; string safePath = GetShortenedPath(basePath, longRelative); Console.WriteLine("Original length: " + Path.Combine(basePath, longRelative).Length); Console.WriteLine("Shortened length: " + safePath.Length); Console.WriteLine("Shortened path: " + safePath); } }
The custom path shortening algorithm reduces component lengths while preserving path structure. This example demonstrates a simple approach to making long paths manageable.
The solution trims each path component to 6 characters plus a tilde. More sophisticated algorithms could use hashing or database lookups. This technique shows how to work within system limitations creatively.
Source
PathTooLongException Class Documentation
This tutorial covered handling PathTooLongException in C#, including prevention techniques, workarounds, and custom solutions for long paths.
Author
List all C# tutorials.