Possible Duplicate:
How to test if a file is fully copied in .NET
As of almost 2012, is there still no better way to check if a file is fully copied as to open it within a try~catch block?
I know it’s been asked before and I’ve checked the automatic related questions Stack Overflow offers, but they are over two years old, so perhaps a better solution exists today?
This is a similar question of 2009:
How to test if a file is fully copied in .NET
EDIT: I changed the question’s title since it raised “requestioning” issues.
No, there still isn’t a way to do that without using
try ... catch, and if I were you I wouldn’t hold my breath waiting for one.What you’re really asking for is a group of functions that can tell you whether or not an attempt to open a file in a particular mode will succeed. Something like a
File.CanOpenForExclusiveRead()or something similar. There are no such methods in .NET, and they don’t exist in the Windows API. And for good reason.Let’s say that such a function existed. That is, you could write:
Sounds like a good idea, right? Except you’d still need to put a
try ... catcharound theFileStreamconstructor because some other thread (perhaps in another process) might open the file for exclusive read between the time your code checked and the time your code called the constructor. Or something else could go wrong: the file could be deleted, the disk could go offline, etc.To be sure, that fictional
File.CanOpenForExclusiveReadmethod would be useful in some cases. Those cases, though, are few and far between, and as I showed above they wouldn’t do you a whole lot of good anyway, since you’d still have to handle possible exceptions anyway.If you want a method that does that, write your own that uses
try ... catchand returnsfalseif an exception is thrown. At least then you hide the details of the implementation. But don’t wait for a better solution. It’s highly unlikely that one is forthcoming.