Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How should I check if a file can be opened for Read, including cases like the file is in use in another process?
I can catch the IOException where I get:
"The process cannot access the file 'C:\...' because it is being used by another process."
but I'd rather check for Read-ability in advance, and control the error message.
(I know this leaves a "window of opportunity" between the checking and the file opening, but in this case the nature of the file is that the user may have opened it manually, so pre-checking should catch most cases, and catching the exception will handle the rest.)
Suggestions?

[Edit: So it appears that it is not a good idea to even try. Which may be why there's no easy way to do it. The best I could find is getting the HRESULT of the exception in the reference from Richard Bishop's solution. At least I can give simplified error messages for the detectable conditions.]
Posted
Updated 14-Nov-13 11:26am
v2
Comments
BillWoodruff 14-Nov-13 17:03pm    
I think you will benefit from the excellent analysis here of issues in determining File availability:

http://stackoverflow.com/a/265958/133321

 
Share this answer
 
I would create a function something like this:

C#
public static bool TryOpenRead(this System.IO.FileInfo file, out System.IO.FileStream fileStream)
{
    fileStream = null;

    try
    {
        fileStream = file.OpenRead();

        return true;
    }
    catch (System.IO.IOException ioException)
    {

    }

    return false;
}


Which, of course, is an extension method for FileInfo[^].

Thats at least the only reliable way to both see if the file is available for reading AND get the file at the same time.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900