The difference between File.Copy and File.Move

I am currently dealing with a small application that updates the mssql compact database files on the iss server.

I prefer to use SSIS to organize the flow. He worked well for a couple of days, but then he started to make mistakes.

In SSIS, I used the Move File operation File System to move the generated files from a folder to a shared folder. If this fails, in the case of a locked file, he tries to execute it later. But I saw that sometimes the files in the destination folder started to disappear.

Then I decided to write my own code. I deleted the "File System Task" and set the "Script Task" instead. And write a couple of lines.

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. But I tried this by locking the destination file. I have included the destination file in Sql Server Management Studio (this is an sdf file). And with surprise, this also works.

And I tried this from the operating system, copying the source file and pasting it into the destination. Windows 7 asks me if I want to overwrite it, and I say yes, and it overwrites the file (copy and replace) that I use with another process, without warning. But if you try to rename or delete it, it will not allow me to do this. Or, if I try to cut and paste it (Move and Replace), it says "you need permission for this action."

As I understand it, Copy, Delete, and Move are completely different things. And I still can not figure out how to overwrite a locked file.

Any ideas?

+8
c # file file-io
source share
1 answer

The File.Move method can be used to move a file from one path to another. This method works on disk volumes and does not throw an exception if the source and destination are the same.

You cannot use the Move method to overwrite an existing file. If you try to replace the file by moving the file with the same name to this directory, you will get an IOException. To overcome this, you can use a combination of copy and delete methods

Answer orignal from: Difference between copy / delete and Move file execution

+5
source share

All Articles