C# Application, unable to delete image because the system has it locked

53 Views Asked by At

I have the following block of code:

    resultImage = args.Image;
    int fileCount = Directory.GetFiles("C:\\ImagesFolder\\").Length;
    temp_num = fileCount;
    string new_num;
    if (temp_num < 10) new_num = "000" + temp_num.ToString();
    else new_num = "00" + temp_num.ToString();
    String filename = 'uploaded_doc_' + new_num + '.jpg';
    temp_num = temp_num + 1;
    var lbitem = new lbItem();
    lbitem.value = filepath + filename;
    lbitem.text = filename;
    listboxScanned.Items.Add(lbitem.text);
    resultImage.Save(filepath + filename);
    resultImage.Dispose();

My delete code has gone between deleting the directory and the individual files, but neither will work as they essentially do the same thing:

    System.IO.Directory.Delete(path, true);

As seen above, it goes through the motions of populating a list box, but when i call the delete after disposing of it, it crashes saying it cannot do it because it is locked by another application. Upon investigating I found the offending application to be itself.

I have tried other methods such as reading it into a file stream, but the code I use obviously doesnt work.

Any help would be greatly appreciated,

0

There are 0 best solutions below