MadBoy
MadBoy

Reputation: 11114

Method to delete files in c#

I have this simple method of deleting list of files. But for some cases it fails to delete the file unless i give it Sleep for some seconds. This is visible especially when i merge Word Documents using Interop and then right after executing merging i try to delete the files it fails to do so for some of them (as i guess Word is still in background).

What would be your approach on this one? Have it async and make it spawn a thread that would start deleting files after a while (kinda like garbage collector?)

    public static void deleteDocuments(List<string> arrayList) {
        foreach (var item in arrayList) {
            try {
                File.Delete(item);
            } catch (Exception e) {
                MessageBox.Show("Błąd kasowania: " + e.ToString(), "Błąd Kasowania", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
        }
    }

Upvotes: 1

Views: 2445

Answers (1)

pstrjds
pstrjds

Reputation: 17448

I agree, this question should be on StackOverflow, but I don't have the cred to move it, so I will add a possible answer and then if it gets moved over, you will probably get a much better answer. You could do something like this:

public static void deleteDocuments(List<string> arrayList)
{
    int maxRetries = 50;
    foreach (var item in arrayList)
    {
        bool retry = false;
        int retryCount = 0;
        do
        {
            try
            {
                File.Delete(item);
            }
            catch(IOException ex)
            {
                // This indicates file is in use, so sleep for
                // half second and retry
                retryCount++;
                if (retryCount < maxRetries)
                {
                    System.Threading.Thread.Sleep(500);
                    retry = true;
                }
                else
                {
                    MessageBox.Show("Błąd kasowania: " + e.ToString(),
                        "Błąd Kasowania", MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Błąd kasowania: " + e.ToString(),
                    "Błąd Kasowania", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
        while(retry)
    }
}

Upvotes: 1

Related Questions