Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to work around the PathTooLongException that FileSystemInfo.Fullname throws sometimes?

I have files on my hard drive that throw a PathTooLongException when I access the Fullname property of a FileSystemInfo object. Is there any way around this (excluding renaming the files which is not an option)?

http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#maxpath mentioned by other answers suggests putting a "\?\" prefix on the file name but in this case the DirectoryInfo.GetFileSystemInfos() is responsible for creating the FileSystemInfo objects and DirectoryInfo doesn't accept that prefix so there's no way to use it.

The answer " PathTooLongException in C# code " doesn't help because this is a multi-threaded application and I can't keep changing the current application path.

Do I really have to do everything with PInvoke just to be able to read every file on the hard drive?

like image 531
Ian Mercer Avatar asked Aug 22 '11 20:08

Ian Mercer


2 Answers

As of Windows 10 (or Windows Server 2016) and .Net 4.6.2, long paths can be supported directly if a registry setting is turned on, and your application is marked as being "long path aware".

The setting can be accessed via the Local Group Policy Editor (gpedit.msc), under Computer Configuration > Administrative Templates > All Settings > Enable Win32 long paths

In order to mark your application as "long path aware", add this section to your manifest file:

<application xmlns="urn:schemas-microsoft-com:asm.v3">
  <windowsSettings>
    <longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
  </windowsSettings>
</application>

Additionally, if your application targets a version of the .Net framework earlier than 4.6.2, you'll need to add a section to your App.config file:

<configuration>
  <runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
  </runtime>
</configuration>

For more information see:
https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/ https://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx

(As far as I know, this only affects the basic Windows filesystem APIs. Non-filesystem APIs may still be limited to 260 characters)

like image 129
camerondm9 Avatar answered Oct 24 '22 05:10

camerondm9


This looks interesting ... Codeplex Long Path Wrapper

The long path wrapper provides functionality to make it easier to work with paths that are longer than the current 259 character limit of the System.IO namespace. Using the long path classes, projects can now use paths up to 32,000 characters.

I'll give that a try, though I note immediately it doesn't provide an equivalent method to DirectoryInfo.GetFileSystemInfos() so it's going to need some modification.

like image 3
Ian Mercer Avatar answered Oct 24 '22 03:10

Ian Mercer