vicki vicki - 26 days ago 9
Vb.net Question

change extension and move file, using vb.net

I have the following code, which changes the extension of a txt to doc, and then moves it (from d:\1 to d:\2). The extension changes successfully, but it does not move, and I get an error


Cannot create a file when that file already exists.


Please suggest.

For Each filePath In Directory.GetFiles("D:\1", "*.txt")
File.Move(filePath, Path.ChangeExtension(filePath, ".doc"))
Next
Dim filesToMove = From f In New DirectoryInfo("d:\1").EnumerateFiles("*.doc")
For Each f In filesToMove
f.MoveTo("d:\2")
Next

Answer

This will check for an existing file of the same name and delete it first (you may want to handle this differently). It will then move and rename in one call to File.Move

Dim directory1 = "D:\1"
Dim directory2 = "D:\2"
For Each oldFileName In Directory.GetFiles(directory1, "*.txt")
    Dim newFileName = Path.ChangeExtension(oldFileName, ".doc").Replace(directory1, directory2)
    If File.Exists(newFileName) Then File.Delete(newFileName)
    File.Move(oldFileName, newFileName)
Next