clweeks
Member
- Joined
- Feb 21, 2007
- Messages
- 18
- Programming Experience
- 3-5
Hi, I have what must be a simple problem and I just need an extra pair of eyes. I'm looping through each FileInfo in a DirectoryInfo.GetFiles and then moving them to a new location. The app moves all of them but the last, at which point it barfs out a "process could not access the file <filename> because it is being used by another process." Worse yet, this code is snipped from a console app that I wrote a while back that works fine.
So, I expect I'm having a brain-fart, who wants to point it out to me? Also, I've swapped out the mechanics of how it's copying (source.moveto, etc) and it's still just the same error. The fact that only the final file (irrespective of what that file actually is) is a problem is bothering me.
VB.NET:
Private Function fileMover(ByVal sourcePath As String, ByVal destPath As String, ByVal delete As Boolean) As Boolean
'If the source path ends with a "\" then we're instantiating a directoryInfo and moving all the files
'in the directory (not recursing down), else we're instantiating a fileInfo and just moving that file.
Dim fileGrabber As New FileInfo(sourcePath)
Dim dirGrabber As New DirectoryInfo(sourcePath)
If sourcePath.Substring(sourcePath.Length - 1, 1) = "\" Then Return fileCopy(dirGrabber, destPath, delete) Else Return fileCopy(fileGrabber, destPath, 1, delete)
End Function
Private Function fileCopy(ByVal source As DirectoryInfo, ByVal dest As String, ByVal delete As Boolean)
If Not Directory.Exists(dest) Then Directory.CreateDirectory(dest)
For Each file As FileInfo In source.GetFiles
If Not fileCopy(file, dest & file.Name, 1, delete) Then Return False
Next
Return True
End Function
Private Function fileCopy(ByVal source As FileInfo, ByVal dest As String, ByVal depth As Int16, ByVal delete As Boolean)
If depth = 5 Then Return False
If dest.Substring(dest.Length - 1, 1) = "\" Then dest &= source.Name
If Not Directory.Exists(dest) Then Directory.CreateDirectory(dest)
If source.CopyTo(dest).Length = source.Length Then
If delete = True Then source.Delete()
Return True
Else
fileCopy(source, dest, depth + 1, delete)
Return False
End If
End Function
So, I expect I'm having a brain-fart, who wants to point it out to me? Also, I've swapped out the mechanics of how it's copying (source.moveto, etc) and it's still just the same error. The fact that only the final file (irrespective of what that file actually is) is a problem is bothering me.