简体   繁体   中英

C# crashes when trying to delete non-existent folder

So basically now I'm struggling to add a if statement to the code... it keeps crashing the application if the directory isn't found. I'd like to add that if the directory isn't found, it'll return a error message into the console which would be Console.WriteLine("Directory not found.. Aborted.");

Code that I'm currently using:

Console.WriteLine("Removing....");

new System.IO.DirectoryInfo( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData ) + "/Testing4121" ).Delete( true );

Console.Clear();

Step 1: Maintainability

I'm not a fan of anonymous objects, so let's do this:

Console.WriteLine("Removing....");

String appDataPath = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
String targetPath  = appDataPath + "/Testing4121";

DirectoryInfo targetDir = new DirectoryInfo( targetPath );
targetDir.Delete( recursive: true );

Console.Clear();

Step 2: Using the correct System.IO APIs:

Use Path.Combine to concatenate path components, not string concatenation:

Console.WriteLine("Removing....");

String appDataPath = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
DirectoryInfo targetDir = Path.Combine( appDataPath, "Testing4121" );

targetDir.Delete( recursive: true );

Console.Clear();

Step 3: Checking for existence:

The simplest solution to your problem is to guard .Delete with if( DirectoryInfo.Exists ) :

Console.WriteLine("Removing....");

String appDataPath = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
DirectoryInfo targetDir = Path.Combine( appDataPath, "Testing4121" );

if( targetDir.Exists )
{
    targetDir.Delete( recursive: true );
}

Console.Clear();

Step 4: Handling exceptional situations:

...that said, other errors can occur when deleting a folder besides directory-does-not-exist, so we should catch those - but only those which should be caught (ie only catch specific Exception -subclasses, only catch Exception itself if you know what you're doing - or you're re-throwing it after performing error logging).

Console.WriteLine("Removing....");

String appDataPath = Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData );
DirectoryInfo targetDir = Path.Combine( appDataPath, "Testing4121" );

if( targetDir.Exists )
{
    try
    {
        targetDir.Delete( recursive: true );
    }
    // See the "Exceptions" list in the documentation for `DirectoryInfo.Delete` to see what to catch: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.delete?view=netcore-3.1
    catch( UnauthorizedAccessException uaEx )
    {
        Console.WriteLine( "Cannot delete directory: a read-only file exists in the directory." );
    }
    catch( DirectoryNotFoundException nxDirEx )
    {
        Console.WriteLine( "Directory was unexpectedly deleted by another program while I was trying to delete it." );
    }
    catch( IOException ioEx ) // while this includes DirectoryNotFoundException, that's caught above.
    {
        Console.WriteLine( "Unexpected IO error: " + ioEx.ToString() );
    }
    catch( SecurityException secEx ) // Don't confuse SecurityException with UnauthorizedAccessException.
    {
        Console.WriteLine( "You do not have permission to delete this directory or a subdirectory thereof." );
    }
    // DO NOT use `catch( Exception ex )` unless the exception is re-thrown using `throw;` to avoid swallowing exceptions that should be caught by a caller higher-up in the call-stack.
    // Only ever use `throw;`, NEVER USE `throw ex;` because that resets the stack-trace: https://learn.microsoft.com/en-us/visualstudio/code-quality/ca2200?view=vs-2019
    catch( Exception ex )
    {
        Console.WriteLine( "An unexpected error occurred. Re-throwing." );
        throw;
    }
}
else
{
    Console.WriteLine( "The directory does not exist - no need to delete it." );
}

Console.Clear();

You can simply put it in a try catch block. Then it automatically ouputs to the console when an error occurs:

        try
        {
            Console.WriteLine("Removing....");
            new System.IO.DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/Testing4121").Delete(true);
            Console.Clear();
        }
        catch(Exception e)
        {
            Console.WriteLine($"{ e }: Directory not found.. Aborted.");
        }
if(Directory.Exists(path))
{
  // This path is a directory
}
else
{
  Console.WriteLine("{0} is not a valid file or directory.", path);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM