This is really hard for me because I dont know the correct term used for this but essentially what I want to accomplish is.. If my code cant execute it jumps over and tried the next thing.. Not sure if I need to use a try & catch loop but here it goes.
As you can see I am trying to delete stuff from my temp folder with a press of a button and it throws me a error on my PC saying that
Access to the path "file name" is denied.
I would like the code to overlook that and jump to the next file and try that one or even better just give the code access to delete the file, not if the file is in use of course.
Is this possible?
private void label6_Click(object sender, EventArgs e)
{
string tempPath = Path.GetTempPath();
DirectoryInfo di = new DirectoryInfo(tempPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
}
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch(Exception e)
{
// Log error.
}
}
Just catch required exceptions (and in your case ignore them):
private void label6_Click(object sender, EventArgs e)
{
string tempPath = Path.GetTempPath();
DirectoryInfo di = new DirectoryInfo(tempPath);
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch (IOException)
{
// ignore all IOExceptions:
// file is used (e.g. opened by some other process)
}
catch (SecurityException) {
// ignore all SecurityException:
// no permission
}
catch (UnauthorizedAccessException)
{
// ignore all UnauthorizedAccessException:
// path is directory
// path is read-only file
}
}
}
What you want is a very common programming feature called Exception Handling, or Error Handling. Using this feature allows you to tell the code what to do if an exception is thrown. In C# (and most languages), you use a try-catch block. At it's most basic, it looks like:
try
{
file.Delete();
}
catch(Exception e)
{
//log error or display to user
}
//execution continues
If file.Delete()
throws an exception, the exception will be 'caught' in the catch
block, and you can then examine the exception and take action accordingly, before continuing on.
Some resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With