Question

I want to copy, rename, and move a file to a new location. According to http://msdn.microsoft.com/en-us/library/36xbexyf(v=vs.90).aspx the following code should do so:

This example copies the file Test.txt to the directory TestFiles2 and renames it NewFile.txt.

My.Computer.FileSystem.CopyFile _
("C:\UserFiles\TestFiles\test.txt", _
"C:\UserFiles\TestFiles2", "NewFile.txt", FileIO.UICancelOption.DoNothing)

However, when I type this code it only sees the "NewFile.txt" parameter as the Boolean parameter that handles overwrites. I believe this is a mistake on the websites part.

If I can't use "My.Computer.FileSystem.CopyFile" (unless I am doing something wrong) to copy rename and move a file, is there a better way then this:

' Rename the file to be copied the name you want it to be in the new location
My.Computer.FileSystem.RenameFile("C:\OriginalFile.txt", "OriginalFileTemporaryName.txt")

' Copy the file to the new location and overwrite if it exists there
My.Computer.FileSystem.CopyFile ("C:\OriginalFileTemporaryName.txt", "C:\UserFiles\TestFiles2", True)

' Rename the original file back to it's original name
My.Computer.FileSystem.RenameFile("C:\OriginalFileTemporaryName.txt", "OriginalFile.txt")

The problem I have with the above is that I might end up renaming the original file a temporary name that already exists in the original files location. I want to avoid that. I also do not want to rename the copied file in the destination folder because I do not see an option to force an overwrite for "My.Computer.FileSystem.RenameFile"

Is this even a half decent solution? Is there not a better way to do this?

Was it helpful?

Solution 2

It certainly looks like a mistake on the website. That shouldn't stop us, though; just put the directory and filename into the same parameter:

My.Computer.FileSystem.CopyFile("C:\UserFiles\TestFiles\test.txt", "C:\UserFiles\TestFiles2\NewFile.txt", FileIO.UICancelOption.DoNothing)

(If you want to force an overwrite, change the third parameter to True. I don't know that you can overwrite and pass CancelOption.DoNothing in the same call.)

OTHER TIPS

I think you have syntax error. You are trying to give the target file name as two parameters - directory name and file name, when you should give both as one string.

 My.Computer.FileSystem.CopyFile ("C:\UserFiles\TestFiles\test.txt", "C:\UserFiles\TestFiles2\NewFile.txt")

Like that. Third parameter could be boolean (True/False) - whether or not you wouldd like to overwrite the target file if it exists.

If you want to first check whether the file exists, take a look at System.IO.File class, it has "Exists" method, which accepts file name and returns boolean. It has also methods to manipulate files which you can use instead of FileSystem class, although there is no performance advantage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top