Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid System.IO.PathTooLongException?

Tags:

c#

.net

We constantly run into this problem...

Example:

if I have a file that I want to copy it into an another directory or UNC share and if the length of the path exceeds 248 (if I am not mistaken), then it throws PathTooLongException. Is there any workaround to this problem?

PS: Is there any registry setting to set this path to a longer char set?

like image 233
theKing Avatar asked Feb 09 '09 21:02

theKing


4 Answers

As described in Jeremy Kuhne's blog, .NET Framework 4.6.2 removes the MAX_PATH limitation where possible, without breaking backwards compatibility.

like image 60
Mark Hurd Avatar answered Nov 15 '22 16:11

Mark Hurd


Try This : Delimon.Win32.I​O Library (V4.0) This library is written on .NET Framework 4.0

Delimon.Win32.IO replaces basic file functions of System.IO and supports File & Folder names up to up to 32,767 Characters.

https://gallery.technet.microsoft.com/DelimonWin32IO-Library-V40-7ff6b16c

This library is written specifically to overcome the limitation of the .NET Framework to use long Path & File Names. With this library you can programmatically browse, access, write, delete, etc files and folders that are not accessible by the System.IO namespace.Library

Usage

  1. First add a reference to the Delimon.Win32.IO.dll to your project (Browse to the Delimon.Win32.IO.dll file)

  2. In your Code File add "using Delimon.Win32.IO"

  3. Use normal File & Directory Objects as if you are working with System.IO

like image 38
Elshan Avatar answered Nov 15 '22 17:11

Elshan


This has been discussed in depth by the BCL team, see the blog entries

In essence there is no way to do this within .Net code and stick to the BCL. Too many functions rely on being able to canonicalize the path name (which immediately triggers the use of functions expecting MAX_PATH to be obeyed).

You could wrap all the win32 functions that support the "\\?\" syntax, with these you would be able to implement a suite of long path aware functionality but this would be cumbersome.

Since a vast number of tools (including explorer[1]) cannot handle long path names it is inadvisable to go down this route unless you are happy that all interaction with the resulting file system goes through your library (or the limited number of tools that are built to handle it like robocopy)

In answer to your specific need I would investigate whether the use of robocopy directly would be sufficient to perform this task.

[1] Vista has ways to mitigate the issue with some fancy renaming under the hood but this is fragile at best)

like image 9
ShuggyCoUk Avatar answered Nov 15 '22 17:11

ShuggyCoUk


Only 1 workaround that I've seen on this one... this might be helpful

http://www.codeproject.com/KB/files/LongFileNames.aspx

like image 4
Brandon Avatar answered Nov 15 '22 16:11

Brandon