Reputation: 37
public void countdown()
{
label1.Text = "0";
label2.Text = "4";
label3.Text = "59";
h = Convert.ToInt32(label1.Text);
m = Convert.ToInt32(label2.Text);
s = Convert.ToInt32(label3.Text);
label1.Text = "0";
label2.Text = "4";
label3.Text = "59";
timer1.Start();
}
private void timer1_Tick_1(object sender, EventArgs e)
{
string hh = Convert.ToString(h);
string mm = Convert.ToString(m);
string ss = Convert.ToString(s);
label1.Text = hh;
label2.Text = mm;
label3.Text = ss;
s = s - 1;
if (s == -1)
{
m = m - 1;
s = 59;
}
if (m == -1)
{
h = h - 1;
m = 59;
}
if (h == 0 && m == 0 && s == 0)
{
timer1.Stop();
MessageBox.Show("Times up! You lost");
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string path2 = "\\Puzzle";
string fullpath = path + path2;
DirectoryInfo di = new DirectoryInfo(fullpath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
}
So Im making a mini-game(here is only the countdown timer) where you choose files then they go to a folder called Puzzle in your desktop and you have 5 minutes to finish a random puzzle and if you don´t, it will delete all files inside the folder. This might seem so stupid but I do a lot of this games with my best friends. Anyways, my question is: I noticed that, if It attempts do delete one of the files and it fails because that file is opened, it gives an Unhandled exception and doesn´t delete the rest of the files. Is there anyway I can make it ignore that unhandled exception and just continue to delete the other files ignoring that one? SOrry for so many text.
Upvotes: 0
Views: 327
Reputation: 332
Wrap the code used to delete a file in a try-catch block, and do nothing in the catch.
try
{
file.Delete();
}
catch (IOException e)
{
// do nothing
}
Do this try-catch block for the directories as well.
Upvotes: 0
Reputation: 540
Wrap your code in a try-catch:
try {
// Put delete logic here
}
catch {
// Do nothing
}
This works, but a better practice is to catch a specific exception type. Since various types of exceptions could be thrown, it is a good idea to only ignore the specific exception you are anticipating. For instance, if a file is in use when C# is attempting to delete it, an IOException
is thrown.
catch (IOException ex) {
// Do nothing
}
Upvotes: 2