Skip to content

Don't catch all exceptions in Directory.CreateDirectory example #11274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,29 +8,30 @@ public static void Main()
{
// Specify the directory you want to manipulate.
string path = @"c:\MyDir";


// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}

DirectoryInfo di;
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}

// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));

// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
catch (UnauthorizedAccessException e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
Console.WriteLine("The caller does not have the required permission to create `{0}`", path);
return;
}
finally {}

// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
}
// </Snippet1>
// </Snippet1>