Is there a reliable way to recognize IOExceptions caused by locked files other than parsing the .message attribute?

As an example, suppose the following VB.NET code snippet to delete a directory.

 Try
      Dim SomeFolder="c:\somefolder"
      System.IO.Directory.Delete(SomeFolder, True)    
 Catch ioex As System.IO.IOException     
     'What went wrong? 
     'File locked by another process? 
     'File not found? 
     'something else?
 End Try       

In the exception handler, if the directory or file inside it is open, I would like to give the user the opportunity to close the file and retry the operation, but only if the IOEx exception was caused by a lock problem.

The problem is that an IOException can be raised for several reasons, for example, an invalid path or a read-only flag set in the file. Each of these conditions sets a different value in the .message attribute of the exception object, but it just feels so wrong to hard code a specific line check in the error message to determine the specific cause of the failure. I don’t have much confidence that the error strings will be consistently formulated with future versions of .net, and I would not want to worry about writing localization code in order to deal with the possibility of returning a message to something other than English.

There should be a better way to deal with what should be an extremely common exception handling problem. Did I miss something?

/: , , , . , .

+3
2

, IOException.

DirectoryNotFoundException, FileNotFoundException .

:

Try
  Dim SomeFolder="c:\somefolder"
  System.IO.Directory.Delete(SomeFolder, True)    
Catch fnfex As System.IO.FileNotFoundException     
 'What went wrong? 
 'File not found? 
Catch ioex As System.IO.IOException     
 'What went wrong? 
 'something else?
End Try       

/ . , :

Dim SomeFolder="c:\somefolder"

If Directory.Exists(SomeFolder) Then
   System.IO.Directory.Delete(SomeFolder, True)
End If

2:

. , , FileLockedException : (

+7

, . :

if (Directory.Exists(SomeFolder))
{
    Directory.Delete(SomeFolder, true);
}

, , , , IOException.

: , , , .

: OP , . , , , , , . :

if (object != null)
{
    object.Value = true;
}

- , catch ( ):

try
{
    object.Value = true;
}
catch NullRefrenceException
{
    ...
}
catch Exception
{
    ...
}

: OP . , , , , , . -, . .

+2

Source: https://habr.com/ru/post/1732053/


All Articles