Difference between File.Copy and File.Move

Viewed 14590

Nowadays I am dealing with a small application which updates the mssql's compact database files on an iss server.

I've preferred to use SSIS to organize the flow. For couple of days it worked well, but then started to give errors.

In SSIS I've used the "File System Task"s "Move File" operation to move generated files from a folder to iss server's shared folder. If it fails, in case of a locked file, it tries it later. But I've seen that sometimes the files in the destination folder started to disappear.

Then I've decided to write custom code. I've removed the "File System Task" and put a "Script Task" instead of it. And write a couple of lines in it.

string destinationFile, sourceFile;
destinationFile = Path.Combine(Dts.Variables["FileRemoteCopyLocation"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());
 sourceFile = Path.Combine(Dts.Variables["OrginalFilePath"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());


bool written = false;


 try
 {
     File.Copy(sourceFile, destinationFile, true);
     File.Delete(sourceFile);
     written = true;
 }
 catch(IOException) {
    //log it
 }


if (written)
     Dts.TaskResult = (int)ScriptResults.Success;
else
     Dts.TaskResult = (int)ScriptResults.Failure;

It worked well. But I tried it by locking the destination file. I've connected the destination file in Sql Server Management Studio (it is an sdf file). And surprizingly it works too.

And I've tried it from operating system, by copying the source file and pasting it to the destination. Windows 7 asks me if I want to overwrite it and I say yes and it overwrote the file (copy and replace) I use with another process, no warning no error. But if try to rename or delete it does not let me to do that. Or if I try to cut and paste it (Move and Replace) it says "you need permission to do this action".

As I understood, "Copy, delete" and "Move" are totally different things. And I still can not understand how can I overwrite a locked file.

Any ideas?

2 Answers

Although the subject is not new, I would like to share my experience. I had to change the pdf file names in my digital library. When I copied about 10,000 legal articles to another folder by changing their names using the File.Copy() method, half of it took about 15 minutes, and I stopped the process because of it takes so long. Then when I tried the same thing with the File.Move() method, the result was incredible for me: It took less than 1 minute to move the whole thing. Of course, I don't need to say that all these are directly related to the system features.

Related