0

the situation: Files are being dumped in a folder. This folder is being constantly monitored with own logic. When files are in the folder they are being processed automatically. We only want to process files that are fully copied into the directory. In case we copy a large file e.g. 100MB to a folder, we don't want to process that file until it is fully copied ('complete').

Currently we test this with this code:

FileStream fs = null;

try {
 fs = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);

// file is 'complete'
} catch (System.Security.SecurityException) {
   // file is locked, don't do stuff (maybe Windows Explorer is still copying).
}
catch {}
finally {
fs?.Close();
}

As I think the SO User Hans Passant once said, the only way to test this is to try opening this file.

This code works but is 'old'.

Are there more efficient methods/techniques to implement and test this? (as performance is critical, the faster, the better).

Falco Alexander
  • 3,092
  • 2
  • 20
  • 39
juFo
  • 17,849
  • 10
  • 105
  • 142
  • What signal do you have for "completion" ? How does the listener know the sender is finished ? – Holger Jan 10 '20 at 11:16
  • why do you think the code is old and thus bad? Why do you think there is anything "newer"? Unless you have good reason not to use that code, why bother if it is old or not? In particular if it gets its job done... – MakePeaceGreatAgain Jan 10 '20 at 11:19
  • I came accross this answer some time ago - checking for file locks without opening a file: . May be of interest to you. – SnowGroomer Jan 10 '20 at 11:24
  • sounds very similar to: https://stackoverflow.com/questions/10982104/wait-until-file-is-completely-written – Falco Alexander Jan 10 '20 at 12:36
  • @HimBromBeere maybe because it might slow? Maybe because .net 4.x has new functionalities? Monitor class? – juFo Jan 10 '20 at 13:05

0 Answers0