65.9K
CodeProject is changing. Read more.
Home

Delete Files that Break Through Maximum Path Length Limitation

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Oct 30, 2014

CPOL

1 min read

viewsIcon

14900

Explains how to delete a local file whose path exceeds the system-defined maximum length

Introduction

This tip shows how to delete a local file whose path exceeds the system-defined maximum length.

Background

Normally, we can use File.Delete to delete a local file given the file path. However, when the file path exceed?s the system-defined maximum length (say 260 characters on Windows, as shown in the Fig. 1), File.Delete will throw System.IO.PathTooLongException.

Figure 1. Example file name beyond the limit

What is Maximum Path Length Limitation?

In the Windows API, the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. See here for more details.

How Comes a File Breaks through the Maximum Path Length Limitation?

The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. This type of path is composed of components separated by backslashes, each up to the value returned in the lpMaximumComponentLength parameter of the GetVolumeInformation function (this value is commonly 255 characters).

Solution

Instead of calling File.Delete, you can use 'del [file_name]' in Windows DOS command prompt to compulsorily delete files.

Using the Code (in C#)

static bool DeleteFile(string fileName)
{
    try
    {
        Process cmd = new Process();

        cmd.StartInfo.FileName = "del";
        cmd.StartInfo.Arguments = fileName;
        cmd.StartInfo.UseShellExecute = false;
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.CreateNoWindow = true;
        cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

        cmd.Start();
        cmd.WaitForExit();
        cmd.Close();
    }
    catch (Exception e)
    {
        // handle the potential exception here
    }
    return !File.Exists(fileName);
}