0

In my VB.net app,

I want to move/Rename a file from folder1 to folder2. Like the following:

   System.IO.File.Move(Folder1 & "1.mp3", Folder2 & "NewName1.mp3")

And then I want to move all the remaining files in folder1 to folder3

   Sub MoveAllFilesToBin()
    Try
        Dim FolderName As New IO.DirectoryInfo(Folder1)
        Dim diar1 As IO.FileInfo() = FolderName.GetFiles()
        For Each CurrFile In diar1
            If System.IO.File.Exists(Folder3 & CurrFile.Name) Then
                System.IO.File.Delete(Folder3 & CurrFile.Name)
            End If
            System.IO.File.Move(Folder1 & CurrFile.Name, Folder3 & CurrFile.Name)


       Next

    Catch ex As Exception

    End Try

End Sub

Looping through this function. I am getting the following error:

 The process cannot access the file because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.__Error.WinIOError()
   at System.IO.File.Move(String sourceFileName, String destFileName)

Does it have to do with Moving first file from folder1 to folder2?

I can't figure out where this error is coming from. I tested it locally and it worked. It only occurs on the server.

Any alternative ways on how to move the first file then move the others?

Should I close and dispose all files before calling MoveFilesToBin()? How can I do that if I'm not opening a filestream?

Any help would be appreciated.

Update:

I tried skipping the part where I move file from folder1 to folder2 and directly called MoveAllFilesToBin() . It worked fine and returned no error.

So the problem is Moving all these files after moving the first one.

HelpASisterOut
  • 3,085
  • 16
  • 45
  • 89
  • 1
    If all of your code is in a single thread, you may be trying to move a file which has been locked by another program, or the system. To be sure it isn't your program locking a file, you can test your second bit of code *without* moving the single file first, or ensure that the first Move operation has completed successfully before attempting the second bulk move. – Justin Ryan May 05 '15 at 08:01
  • @JustinRyan I tried the second bit of code without moving the single file first. It worked. Means the system is still locked after the first Move. How can I dispose it? I am not using StreamReader – HelpASisterOut May 05 '15 at 08:11
  • 1
    Tip: Don't use `Folder1 & CurrFile.Name`. Instead use `Path.Combine(Folder1, CurrFile.Name)`. Path.Combine will take care of creating a proper filename, reducing the chances of errors. – Chris Dunaway May 05 '15 at 16:39

0 Answers0