Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

.NET 2.0 Workaround for PathTooLongException

3.67/5 (11 votes)
17 Dec 2007CPOL 1   2.7K  
Using the Unicode version of CreateFileW, we can overcome the PathTooLongException error on file operations.

Introduction

File operations like File.OpenRead or the FileStream constructor would throw a PathTooLongException when presented with an absolute path of length greater than 260 characters.

Looking at the Win32 API, I found that the CreateFileW (Unicode) version of the function supports long file names up to 32000 characters if the file path is prefixed with a \\?\. I went ahead and created this class that has Open methods similar to File.Open/OpenRead/OpenWrite to make the interface consistent.

Background

In ANSI mode of the CreateFile API, Windows restricts the total file length to 260 characters. You can see this effect when you try to create a new file and rename to something more than 260 characters. Windows will automatically limit you to the total file path=260, starting from c:\.

Using the code

I have attached a class in the System.IO namespace called Win32File. It has the same interface as File.Open/OpenRead/OpenWrite.

C#
//Sample Usage

FileStream fs1= Win32File.Open( "Long file name of greater " + 
                "than 260 char length", FileMode.Open);
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine("Hello world");
sw.Close();
sw.Dispose();

History

  • Version 1.0.
  • Version 1.1 -- Updated code to accommodate UNC paths. The prefix needs to be \\?\UNC\.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)