0

When I am saving a file or creating a directory using system.io by providing a path it gives an error “the specified path, file name or both are too long. The fully qualified domain name must be 260 characters and the directory name must me 240 characters

1). I have tried the Delimon library but still it gives the same error.

2). I have tried to add \?\ prefix but it results in illegal characters.

3). I have also tried: // at the start of the file name but it results in uri not supported error

Now my questions are:

1). Is it possible to use the long path using System.IO library?

2). If you are giving solution by Delimon library, then please tell can I use this library in my shareware software?

Thanks in advance…

Shaharyar
  • 12,254
  • 4
  • 46
  • 66

1 Answers1

0

The basic issue is that the .NET framework specifically does not permit long filenames to be used and will actively work to prevent you from using them. Short of using the Win32 API calls directly to create and write to files you won't be able to simply use a long path.

Depending on the nature of the path you may be able to reduce it to a shorter length. Any file or folder name that does not fit in the 8.3 format will have a shortened version that does. You can use the GetShortPathName API to determine if there is a short form of the path that will fit within the standard limits.

Example:

[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetShortPathNameW", SetLastError = true)]
static extern int GetShortPathName(string pathName, System.Text.StringBuilder shortName, int cbShortName);

static void Main()
{
    StringBuilder sb = new StringBuilder(300);
    int res = GetShortPathName(
        @"C:\Program Files (x86)\GitHub Extension for Visual Studio\GitHub.VisualStudio.vsix", 
        sb,
        300
    );

    Console.WriteLine(sb.ToString());
}

The above prints:

C:\PROGRA~2\GITHUB~1\GITHUB~1.VSI

This will only work for files that exist but can be used to at least shorten the folder name to the shortest level. For borderline cases that might be enough to let you access the files directly.

If not then you'll need to look at a workaround of some sort.

Possibly the simplest is to use a short, simple path for the initial save and then call the Win32 APIs directly to move the file into its final position, with full long path support and all.

You could also try the Pri.LongPath module in NuGet. It lets you work with long filenames, including moving and so on, but I don't think it makes it possible for you to read/write those files when they get over the 260 character limit. Try it and see.

Corey
  • 15,524
  • 2
  • 35
  • 68