Safest way to copy a file
I need to merg two PDF files. However sometimes a file might be locked up
I wrote this code, but I'm wondering if it's not the smartest solution:
private static int FILE_LOCKED_WAIT_PERIOD = 1000;
while (true)
{
// If the file is in use, IOException will be thrown.
// If file is not permitted to be opened because of Permission
// Restrictions, UnauthorizedAccessException will be thrown.
// For all other, Use normal Exception.
try
{
inputDocument1 = PdfReader.Open(fileToMerge, PdfDocumentOpenMode.Import);
break;
}
catch (IOException)
{
Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
}
catc开发者_如何学Pythonh (UnauthorizedAccessException)
{
Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
}
catch (Exception)
{
Thread.Sleep(FILE_LOCKED_WAIT_PERIOD);
}
}
You should add a timer so that you sleep for a few clicks before you try the file operation again.
Also you should have counter so you do not wait indefinitely and that you exit after say 15 tries.
Well this depends: 1) Is it a process that is all internal to a system independent of a user? If so you should try to find out what is locking the file and wait for the explicitly. Waiting randomly and then trying over and over again may cause problems on its own.
2) Is it a user that may have the file open? In this case waiting is not helpful since the system could retry all weekend because the user suddenly left for the day. You have no control over user timing. Just tell the user that you cannot do the requested operation because the file is open and have them try again.
Usually waiting for N seconds/minutes is not really a solution. Either you know what the problem may be and poll & resolve the issue or you can't really do anything and just send out notice.
There is no special function to do this. Actually even if this function exists, some process can still easily lock this file between your "lock check" and "file open"
精彩评论