tags:

views:

1822

answers:

5

How to create a copy of a file having length more than 260 characters including file name using vb.net

When we are trying to create a copy using File.Copy method it throws exception as follows:

"The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."

Is it possible, then please help...

+2  A: 

There are tips for shortening the name ... see the section titled "Cause 4: Files exist in paths that are deeper than MAX_PATH characters" at http://support.microsoft.com/?kbid=320081#

ChrisW
Its a Windows restriction. if the FilePath exceeds 260 characters, most of the file operations would throw similar errors.. Even File Rename would have issues I think
Gishu
Matt's answer (use `CopyFile`) is better than mine.
ChrisW
+5  A: 

You're running into the MAX_PATH limitation. As a work around you should be able to P/Invoke directly to kernel32.dll's CopyFile function and use the "\\?\" Prefix in front of the destination path to prevent hitting the MAX_PATH issue.

Note that while you're able to copy the file in the way most apps won't be able to open it since they are also limited by MAX_PATH.

A good overview of the problem can be found here: http://blogs.msdn.com/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx

Some example code of P/Invoking into these methods using C# can be found in Part 2, here: http://blogs.msdn.com/bclteam/archive/2007/03/26/long-paths-in-net-part-2-of-3-long-path-workarounds-kim-hamilton.aspx

The library that schnaader linked to looks like it will save you the problem of P/Invoking into kernel32.dll, not sure if you want to take a dependency on an external dll or not.

Matt Ellis
A: 

What I usually do in this instance is:

1) Count the file name length

2) If FileNameLength > 259 then crop the file name enough to handle the new name and then copy the file with a cropped destination name.

Matias Nino
A: 

Have a look at this library and this discussion.

schnaader
+1  A: 

I got a solution regarding this issue.

On R&D I found we can rename the specified path directory even though the total length is exceed 260 characters and then we can copy the file from the specified location to new (Temporary) location for our scanning purpose. And finally we can again rename the file path name with original one.

Suman