How to Copy File from One Location to Another: Windows Forms

October 17, 2013 , , 0 Comments

Sometimes, some files are mostly used in our programming field, and we can’t use OpenFileDialog only after a minute and so on. That’s why we have to copy these files in our desired location, so that we can use them as per our requirement.

To copy a file from an existing location, we should have source path and destination path. For source path, we can use open file dialog and for destination path, we can use folder browsing path or even a path in form of string.

Generally System.IO.File namespace is used for handling file functions and events. In our previous post we have create, delete, read or write a text file. Now to copy a file from source to destination, we are just using following function:

System.IO.File.Copy("Source Path", "Destination Path", Boolean value);

This function is as simple as written above. Source and destination path is known to everyone, now the focus is on Boolean value. This Boolean parameter is deciding, whether the file should be overwriten or not. If the value of this Boolean value be
  • True: if the file exist on destination, it will overwrite that. If not exist copy that file.
  • False: if the file exist on destination, it will not copy. If not exist copy that file.
Now look out the following code, it will open an open file dialog, and then copy the selected file to our debug folder of the project.
OpenFileDialog ofd = new OpenFileDialog();
System.IO.File.Copy(ofd.FileName, Environment.CurrentDirectory + "\\"+ ofd.SafeFileName, true);

I have used the true value for Boolean parameter, means it will overwrite the file if exists. So the file has been successfully copied and we can check that using File.Exist(“Path”) function.

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google