473,394 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

solution for PathTooLongException

To traverse folders recursively that contain files with a path 260 chars we can use Unicode versions of FindFirst and FindNext and prefix all paths with NTFS escape sequence '\\?\'.

Files can be opened using SafeFileHandle and Win32 Api function CreateFile.

Here is the code:

/// <summary>
/// count files in starting folder and it's subfolders and retrieve the longest folder (not file!) path
/// </summary>
/// <param name="backgroundWorker">backgroundWorker</param>
/// <param name="e">arguments of backgroundWorker</param>
/// <param name="startFolderPathLong">full path of start folder (long form)</param>
/// <param name="startFolderShortForm">full path of start folder (truncated form)</param>
/// <returns>total number of files in folder (including subfolders)</returns>
int CountFilesInFolder(BackgroundWorker backgroundWorker, DoWorkEventArgs e, string startFolderPathLong, string startFolderShortForm)
{
try
{
if (backgroundWorker != null && backgroundWorker.CancellationPending)
{
e.Cancel = true;
return 0;
}

int numFiles = 0;
Win32Api._WIN32_FIND_DATAW fndData = new Win32Api._WIN32_FIND_DATAW();

IntPtr hFile = Win32Api.FindFirstFileW(_ntfsPrefix + startFolderPathLong + "*", ref fndData); // skip '.'

Win32Api.FindNextFileW(hFile, ref fndData); // skip '..'

int numFilesInThisFolder = 0;
while (Win32Api.FindNextFileW(hFile, ref fndData))
{
if (hFile.ToInt32() == -1)
{
throw new Exception(string.Format("FindNextFileW() in folder '{0}') failed: {1}",
startFolderPathLong,
Marshal.GetLastWin32Error()));
}
else
{
if ((fndData.dwFileAttributes & Win32Api.FILE_ATTRIBUTE_DIRECTORY) == Win32Api.FILE_ATTRIBUTE_DIRECTORY)
{
string folderPathLong = Utils.AppendPathSeparator(startFolderPathLong + fndData.cFileName);
string folderPathShort = Utils.AppendPathSeparator(Utils.RemoveNTFSPrefix(U tils.ToShortPathName(_ntfsPrefix + folderPathLong)));
numFiles += CountFilesInFolder(backgroundWorker, e, folderPathLong, folderPathShort);
if (e.Cancel || (backgroundWorker != null && backgroundWorker.CancellationPending))
{
return 0;
}
}
else // if ((fndData.dwFileAttributes & FILE_ATTRIBUTE_FILE) == FILE_ATTRIBUTE_FILE)
{
++numFilesInThisFolder;
}
}
}

Win32Api.FindClose(hFile);

if (numFilesInThisFolder 0)
{
if (startFolderShortForm.Length Settings.Default.MaxFolderPathShortLength)
{
string msg = string.Format("Length of folder ({0}) path exceeds MaxFolderPathShortLength ({1}) for folder '{2}' (long path = '{3}'",
startFolderShortForm.Length, Settings.Default.MaxFolderPathShortLength, startFolderShortForm, startFolderPathLong);
Error(msg);
}
if (startFolderShortForm.Length _longestFolderPathWithoutFileNameShortForm.Length)
{
_longestFolderPathWithoutFileNameShortForm = startFolderShortForm;
}
}

return numFiles + numFilesInThisFolder;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString() );
return 0;
}
}

public static byte[] ReadAllBytes(string filePathSrc)
{
try
{
SafeFileHandle fileHandle = Win32Api.CreateFile(
filePathSrc,
Win32Api.EFileAccess.GenericRead,
Win32Api.EFileShare.Read,
IntPtr.Zero,
Win32Api.ECreationDisposition.OpenExisting,
0,
IntPtr.Zero);
int lastWin32Error = Marshal.GetLastWin32Error();
if (fileHandle.IsInvalid)
{
throw new System.ComponentModel.Win32Exception(lastWin32Erro r);
}
// Pass the file handle to FileStream. FileStream will close the handle
using (FileStream fileStream = new FileStream(fileHandle, FileAccess.Read))
{
byte[] fileData = new byte[fileStream.Length];
if (fileStream.Length != fileStream.Read(fileData, 0, (int)fileStream.Length))
{
throw new Exception(string.Format("cannot read file '{0}'", filePathSrc));
}
return fileData;
}
}
catch (Exception ex)
{
throw new Exception(string.Format("cannot read from file '{0}': {1}",
filePathSrc, ex.ToString()));
}
}
EggHeadCafe.com - .NET Developer Portal of Choice
http://www.eggheadcafe.com
Jul 23 '07 #1
0 4078

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Wayne Wengert | last post by:
I have a solution. I want to clone it to try some different options. Is there a way to open Solution A, save it as Solution B and then be able to try some things in Solution B without affecting...
10
by: Simon Jefferies | last post by:
Hello, I'm getting a strange problem where when I load up my solution that has three projects:- a managed C++ .NET, one C++ lib, and a VB library. It locks up and doesn't load completely, I...
0
by: TEK | last post by:
Hello We have a quite huge project. To limit the solution size, rebuild time and so on we have divided the project in two different solution. One solution that holds the buiness entities, or...
0
by: Shakil Khan | last post by:
System.IO.PathTooLongException "The path is too long after being fully qualified. Make sure path is less than 260 characters" Can anyone help, How to resolve this issue? This exception is...
2
by: Justin | last post by:
Hi. I'm writing a little c# program to list all the files in a selected directory longer than a given size. The problem is that when it finds a file that is too long for Windows, I get the...
3
by: Manikandan | last post by:
Hi, I'm copying projects from a solution in the vss. In my local system i created solution ,added that project(make modification related to solution) When i added this solution to vss, projects...
0
by: mjheitland | last post by:
When I pass my directories recursively on a directory structure with paths 260 chars I get the following exception (see line marked with ***), although I am using only ShortPathNames through...
0
by: techie | last post by:
List of Solution manuals: Engineering Circuit Analysis 6Ed - Hayt Solutions Manual Norbury - Solutions manual for mechanics and thermodynamics Physics For Scientists And Engineers - Solution...
5
by: Gillard | last post by:
hi , i try to io.file.delete(startmenushortcut) i get PathTooLongException how to delete those dead links in my start menu please
16
by: =?Utf-8?B?RHdlZWJlcmVsbGE=?= | last post by:
I created an Access 2007 application for my customer. The application is shared by three employees on a server. It maintains a contact list including financial data and social security numbers. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.