Skip to content

C# Check if file is unlocked

C# Check if file is unlocked

C# does not provide a way to check if a file is unlocked specifically, hence, you will have to implement your own solution by relying on Exceptions produced and catching them. For example, the use case for the code below is if you want to delete a file immediately when it is unlocked. You can simply replace the delete operation with whatever you wish to do to the file – read, write …
bool fileDeleted = false;
while (!fileDeleted)
{
    try
    {
        //Delete file
        if (File.Exists(orgFilePath))
        {
            File.Delete(orgFilePath);
            fileDeleted = true;
        }
        else
        {
            fileDeleted = true; // file doesn't exists anymore
        }
    }
    catch
    {
      //if you wish to do anything with the exception
    }
}
 
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.