Shayna Shayna - 4 months ago 13
Vb.net Question

I don't understand this exception

I'm trying to make a program that will check if a directory exists and if it does not then create it and move a file into it, if it does exist then don't make the directory but just move the file, although I run into an exception and I don't understand why.

Exception:


An unhandled exception of type 'System.IO.IOException' occurred in Microsoft.VisualBasic.dll

Additional information: Could not complete operation since a directory already exists in this path 'E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup'.


The code I have so far:

Private Sub Backup1_Click(sender As Object, e As EventArgs) Handles Backup1.Click
If Not My.Computer.FileSystem.DirectoryExists("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup") Then
My.Computer.FileSystem.CreateDirectory("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup")
My.Computer.FileSystem.MoveFile("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ScriptHookV.dll", ("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup"))
ElseIf My.Computer.FileSystem.DirectoryExists("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup") Then
My.Computer.FileSystem.MoveFile("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ScriptHookV.dll", ("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup"))
End If

End Sub


The exception would suggest that it won't allow the creation of the directory because the directory already exists, but even when I delete the directory before running the program it still gives me the exception even though it created the directory with no problem, it also does not highlight the line where it creates the directory but rather the line that is responsible for moving the file as the source of the exception.

Some help would be appreciated :)

Answer

It's always best if you show the full stack trace of the error. It would then be clearer that the error occurs when you call MoveFile.

The problem is that the 2nd parameter of MoveFile should be the destination file path, and not the destination directory path.

Right now, the following line:

My.Computer.FileSystem.MoveFile("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ScriptHookV.dll", ("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup"))

... attempts to create a file E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup, which is obviously invalid.

You'll need to change it to:

My.Computer.FileSystem.MoveFile("E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ScriptHookV.dll", "E:\SteamLibrary\steamapps\common\Grand Theft Auto V\ModManagerModBackup\ScriptHookV.dll")