user3043304
user3043304

Reputation:

How to close a file opened by another thread?

I've a background thread which loads an image file using Image.FromFile, I want to close the opened image file from another thread

Is there a possibility to close a file opened by a background thread in c#?

Edit: I used this code at first - on the same thread- but I don't know why I can't free the file or delete it, or even the new file which I saved using img.Save(...). So I tried to force closing on another thread. that's why I'm asking this question.

var img = Image.FromFile(filepath);
img.Save(filepath + ".jpg", ImageFormat.Jpeg);
img.Dispose();
if (File.Exists(filepath+ ".jpg"))
    File.Delete(+ ".jpg");
if (File.Exists(filepath))
    File.Delete(filepath);

Upvotes: 0

Views: 1135

Answers (1)

drew_w
drew_w

Reputation: 10430

The file isn't "Closed" until the image has been disposed. Open and close the file immediately in a single step by loading the image with the following snippet:

System.Drawing.Bitmap image;
using (var fileLoadImage = System.Drawing.Bitmap.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"))
{
    image = new System.Drawing.Bitmap(fileLoadImage);
}

You need to be very careful with this pattern though because you are still going to have to explicitly call image.Dispose() when you are finished with your image. At least this will get you around file locking though.

Best of luck!

EDIT - A Runnable Snippet

Copy and paste the following into a new Console application to see that it works. Make sure you have a file called "test.jpg" in your sample pictures before you start and you will see this deletes both the original file and the new file just fine:

public class Program
{
    public static void Main(string[] args)
    {
        System.Drawing.Bitmap image;
        var originalFile = @"C:\Users\Public\Pictures\Sample Pictures\test.jpg";
        var newFile = @"C:\Users\Public\Pictures\Sample Pictures\test2.jpg";
        using (var fileLoadImage = System.Drawing.Bitmap.FromFile(originalFile))
        {
            image = new System.Drawing.Bitmap(fileLoadImage);
        }

        image.Save(newFile);
        System.IO.File.Delete(originalFile);

        image.Dispose();
        System.IO.File.Delete(newFile);
    }
}

Upvotes: 4

Related Questions