How to make my code skip something if there is a C # .NET error

It is really difficult for me because I don’t know the correct term used for this, but essentially what I want to execute is .. If my code cannot execute it, it jumps and tried the following. Not sure if I need to use a try and catch loop, but here it goes.

As you can see, I am trying to delete material from the temp folder with the click of a button, and this leads me to my computer, saying that

Access to the path "file name" is denied.

enter image description here

I would like the code to skip this and go to the next file and try this one or even better just give the code access to delete the file, and not if the file is used, of course.

Is it 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(); } } 
+6
source share
5 answers
 foreach (FileInfo file in di.GetFiles()) { try { file.Delete(); } catch(Exception e) { // Log error. } } 
+6
source

Just remove the necessary exceptions (and ignore them in your case):

 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 (eg 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 } } } 
+3
source

You need to catch the exception and decide to exit the loop

see this question - How to handle the exception in the loop and continue the iteration?

0
source

You must first add a status check for what might cause the error. If there are other conditions that you cannot control in your code, add a try-catch statement.

0
source

What you want is a very common programming feature called Exception Handling or Error Handling. With this function, you can specify the code of what to do if an exception is thrown. C # (and most languages) uses a try-catch block. He has the most basic thing, it looks like this:

 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 , and you can then examine the exception and take appropriate action before continuing.

Some resources:

0
source

All Articles