Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How do I detect if a file has been locked by another process in powershell?

I have read some examples of checks that catches the exception that occurs when trying to read the file. This some how does not feel good to me.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

In general, you can't be sure that you have the access to a file that you want without actually trying to use it. Even if you could do a proper check, between the time you do the check and the time you use the file, the state could change.

For example, the user supplies you with a file name to read. You check if the file exists, see that it does, and decide to proceed. Before you try to read it, another program deletes it. Or maybe the file is on a network share and the network goes down.

So, try to use the file, catch the exception, and fail gracefully.

Also, remember to only catch and dismiss exceptions that you understand and expect.

share|improve this answer
    
Thank you Jay, you are of course right, I did not think of that. –  elgrego Mar 11 '11 at 19:15
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.