File Deletion Problem

  • Thread starter Thread starter noctufaber
  • Start date Start date
N

noctufaber

I wrote a recursive file/folder copy/delete routine because someone on
the 2.0 .NET development team was too lazy to make directory.move work
across volumes (i.e. moving a folder from drive C: to drive D:).
Anyway, everything works great with the copy routine. The problem
comes up during the File.Delete. Well over a hundred files are
successfully deleted by my routine except for one file. I have
checked the file's security/permission settings and they are IDENTICAL
to the files that successfully delete. I put DoEvents and
Thread.Sleep commands, but they don't work either.

Has anybody seen this and found a solution? My source code is shown
below:
--------------------------------------------------------------------------
Sub DeleteDirectory(ByVal theSrcDir As String)
Dim theDirList() As String =
Directory.GetDirectories(theSrcDir)
Dim dirparts() As String = theSrcDir.Split("\")
Dim trueDest As String = driveLetter
For i As Integer = srcRootIdx To dirparts.Length - 1
trueDest = trueDest & "\" & dirparts(i)
Next

' srcRoot & theSrcDir.Substring(theSrcDir.Length -
srcRoot.Length + 2)

For Each DirItem As String In theDirList
DeleteDirectory(DirItem)
Next

Dim theFileList() As String = Directory.GetFiles(theSrcDir)

For Each FileItem As String In theFileList
Dim BaseNameParts() As String = FileItem.Split("\")
If (Not Directory.Exists(trueDest)) Then
Directory.CreateDirectory(trueDest)
Try
Dim times As Integer = 0
Do
If times > 10 Then Throw New Exception("Stupid
Windows Can't delete a file!!!!!!!")
Try
File.Delete(FileItem) ' HERE IS THE ANNOYING,
FRUSTRATING PROBLEM!!!
Application.DoEvents()
Threading.Thread.Sleep(1000)
Catch ex As Exception
MsgBox(ex.Message)
End Try
times += 1
Loop Until (Not File.Exists(FileItem))
Catch
End Try
Next

Try
Directory.Delete(theSrcDir)
Catch
End Try
End Sub
 
Try the following code which came from the link below. I added one line for
changing the file attributes prior to the deletion, otherwise I got an
exception on my test.

Private Sub DeleteAllSubFolders(ByVal StartPath As String)
Dim myfolder As IO.DirectoryInfo = New IO.DirectoryInfo(StartPath)
Dim mySubfolders() As IO.DirectoryInfo = myfolder.GetDirectories()
Dim strFiles() As IO.FileInfo = myfolder.GetFiles()

For Each myItem As IO.DirectoryInfo In mySubfolders
DeleteAllSubFolders(myItem.FullName)
Next

For Each myItem As IO.FileInfo In strFiles
Try
myItem.Attributes = IO.FileAttributes.Normal
Application.DoEvents()
myItem.Delete()
Catch ex As Exception
Console.WriteLine("{0} failed to delete -- Reason {1}",
myItem.Name, ex.Message)
End Try
Next
myfolder.Delete()
End Sub

Original code: http://www.developerfusion.co.uk/forums/thread/151330/
 
Back
Top