Why doesnt this work???

Joe Mamma

Well-known member
Joined
Mar 1, 2004
Messages
1,062
Location
Washington DC
this is a recursive routine to delete empty sub directories under a given path.
PHP:
private void DeleteEmpty(string aPath)
{
string currPath = System.Environment.CurrentDirectory;
System.Environment.CurrentDirectory = aPath;
string[] directory = Directory.GetDirectories(".");
string[] file = Directory.GetFiles(".");
if ((file.Length + directory.Length)==0)
{
	System.Environment.CurrentDirectory = currPath;
	Directory.Delete(aPath);
}
else
	if (directory.Length>0) 
	 for(int i = 0; i < directory.Length; i++)
		DeleteEmpty(directory[i]);
else
	System.Environment.CurrentDirectory = currPath;
}

Directory.Delete(Path.GetFileName(aPath))
gives error:
An unhandled exception of type System.IO.IOException occurred in mscorlib.dll
Additional information: Access to the path "C:\Practice\Sub1" is denied.
I have the directory structure:
C:\Practice
|_ Sub1

I make a call DeleteEmpty("C:\Practice");
Sub1 is empty.
There is no process locking the path. While In debugging, I can manually delete the folder while the error message is up.
any ideas????
 
Last edited by a moderator:
Just tried it on my PC here and it worked without any problems. Also rather than switching the current directory back and forth (which may be causing a problem) try the following snippet

C#:
private void DeleteEmpty(string aPath)
{
	string[] directory = Directory.GetDirectories(aPath);
	string[] file = Directory.GetFiles(aPath);
	if ((file.Length + directory.Length)==0)
	{
		Directory.Delete(aPath);
	}
	else
		if (directory.Length>0)
        	for(int i = 0; i < directory.Length; i++)
			DeleteEmpty(directory[i]);
      }
 
PlausiblyDamp said:
Just tried it on my PC here and it worked without any problems. Also rather than switching the current directory back and forth (which may be causing a problem) try the following snippet
well the purpose of this was part of a routine for a little utility I wrote that was organizing my mp3/wma collection by artistsortorder/albumsortorder ala

\Music
->\Artist1
->->\Album1
->->\Album2
->\Artist2
->->\Album1

I ran into problems working with with paths that exceed max path length, like

"D:\Music\A Silver Mt Zion\He Has Left Us Alone But Shafts of Light Sometimes Grace the Corners of Our Rooms\A Silver Mt Zion - He Has Left Us Alone But Shafts of Light Sometimes Grace the Corners of Our Rooms - 13 Angles Standing Guard Round the Side of Your Bed.mpg"

I tried using the workaround suggested from MS but that didnt seem to work.
By using relative paths I got around it while moving files. Its not as much an issue when clearing directories. . .

Let me try your code. I might need to reboot, too. I installed the WMP 10 sdk and am working with that. could be a bug there.

thanks
 
Back
Top