0

Step 1- I am copying a file manually by reading from source then writing to target files in chunk. I keep the file handle open until all copy is not over. The handle is safely closed as copy is over.

Step 2- After copy is over, I set the time stamp, attributes, ACL and may more things.

Sometime in step 2, I get the issue that file is being used by some other process. This issue raise mostly for exe files. I got the answer which process was using that file from File locked by other process. A sper answer, OS locks the file to set the icon or some other information on file for a very minor time.

But if I go to perform step 2 without any delay after finishing step 1 then I get access error. How I can ensure that OS will not lock the file?

Looping to check for file access is not an solution as per because the locking may be happen at any point of time in step 2. Step 2 is not atomic, there I need to open/close same file multiple times.

Community
  • 1
  • 1
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
  • If the issue comes from the fact that it is exe file which is in place caused by explorer, then you can write your file with dummy extension and at the very end of your process after stage 2 change the extension to .exe – jekcom Jun 02 '15 at 12:00
  • @jekcom I noticed for exe but I need robust solution. – Romil Kumar Jain Jun 02 '15 at 12:06
  • @Asad, File is not readonly because I am copying manually. so this is not the case. – Romil Kumar Jain Jun 02 '15 at 12:12
  • I assume that step 1 and 2 are done via some kind of FileStream? Can't yo then leave the stream open until step 2 is complete? – jekcom Jun 02 '15 at 12:20
  • @jekcom step 1 is done using FileStream but not true in case of step 2. – Romil Kumar Jain Jun 02 '15 at 12:35
  • Ok, but still you can perform step 2 while the stream is open, and close it after step 2 is done. You just need to specify FileShare.Write parameter e.g. `FileStream fs = new FileStream("file.exe", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Write )` – jekcom Jun 02 '15 at 13:12
  • We can copy the timestamp from source file using FileInfo, so there is not role of file stream. – Romil Kumar Jain Jun 02 '15 at 13:20
  • There are too many possible reasons you could be getting this exception, including some that are your own fault. Please provide [a good, _minimal_, _complete_ code example](http://stackoverflow.com/help/mcve) that reliably reproduces the problem. – Peter Duniho Jun 03 '15 at 03:07
  • @PeterDuniho please check http://stackoverflow.com/questions/30502845/filestream-close-is-not-closing-the-file-handle-instantly – Romil Kumar Jain Jun 03 '15 at 07:18

0 Answers0