Click here to Skip to main content
15,042,089 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,
Actually i am getting this error while trying to delete file.
the process cannot access the file because it is being used by another process

here is my code:
C#
public static byte[] GetTransparentArrayFromFileWithDelete(string pathToFile)
        {
            byte[] newImage = new byte[0];
            using (Bitmap bmp = new Bitmap(pathToFile))
            {
                Color pixel = bmp.GetPixel(0, 0);
                Graphics graphics = Graphics.FromImage(bmp);
                Color backColor = bmp.GetPixel(1, 1);
                bmp.MakeTransparent(backColor);
                ImageConverter converter = new ImageConverter();
                newImage = (byte[])converter.ConvertTo(bmp, typeof(byte[]));
            }
            try
            {
                File.Delete(pathToFile);
            }
            catch
            {
            }
            return newImage;
        }


Can Any one help please!!!
Thanks

What I have tried:

Tried to delete file but this error occurs:
the process cannot access the file because it is being used by another process
Posted
Updated 20-Mar-16 22:12pm
v2

See Bitmap Constructor (String) (System.Drawing)[^]:
Quote:
The file remains locked until the Bitmap is disposed.
So call Dispose() before deleting the file or delete the file after the Bitmap instance has been finalized.
   
Comments
_ProgProg_ 21-Mar-16 4:21am
   
Actually i called bmp.Dispose(); but the same issue occures.
Notice: I am using File.Delete outside bitmap scope.
Any Ideas??
Jochen Arndt 21-Mar-16 4:28am
   
Did you have opened the same file somewhere else in your application or even another application?

You can use the Process Explorer (https://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to check which process has opened the file (just enter the file name when selecting the 'Find' menu item).
_ProgProg_ 21-Mar-16 4:28am
   
Actully i tried again after removing this line of code:
Graphics graphics = Graphics.FromImage(bmp);
And it works fine now..
Thanks alot..
Jochen Arndt 21-Mar-16 4:32am
   
Thank you for your feedback that the problem is solved.

That takes a reference to the bitmap and was therefore probably the reason.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900