c# JpegBitmapEncoder save and overwite

253 views Asked by At

I am trying to add tags to a jpeg file.

However, my algorithm prevents me from overwriting the jpeg file, and allows me only to create a new file.

  static string file = @"C:\temp\check.jpg";
    static void Main(string[] args)
    {
        LosslessJpegTest(new List<string> { "hello","my name is Bob"});
    }

    private static void LosslessJpegTest(List<string> keywords)
    {
        string original = file;
        const BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat;


        Stream originalFileStream = File.Open(original, FileMode.Open, FileAccess.ReadWrite);

        BitmapDecoder decoder = BitmapDecoder.Create(originalFileStream, createOptions, BitmapCacheOption.None);            


        if (decoder.CodecInfo == null || (!decoder.CodecInfo.FileExtensions.Contains("jpg")&& !decoder.CodecInfo.FileExtensions.Contains("jpeg")) || decoder.Frames[0] == null)
            return;

        BitmapMetadata metadata = decoder.Frames[0].Metadata == null
            ? new BitmapMetadata("jpg")
            : decoder.Frames[0].Metadata.Clone() as BitmapMetadata;

        if (metadata == null) return;

        if (metadata.Keywords != null)
        keywords.AddRange(metadata.Keywords);                    

        metadata.Keywords = new ReadOnlyCollection<string>(keywords);

        JpegBitmapEncoder encoder = new JpegBitmapEncoder { QualityLevel = 100 };
        BitmapFrame bmpFrame = BitmapFrame.Create(decoder.Frames[0], decoder.Frames[0].Thumbnail, metadata, decoder.Frames[0].ColorContexts);

        encoder.Frames.Add(bmpFrame);

        Stream newFileStream = File.Open(original, FileMode.Create, FileAccess.ReadWrite);
        encoder.Save(newFileStream);

    }

The execption that is thrown is: System.IO.IOException: 'The process cannot access the file 'C:\temp\check.jpg' because it is being used by another process.'

How can I overwrite the file with the new tags? I wouldn't like to save a temporary file for this purpose, and then replace it with the original.

1

There are 1 answers

3
Dan On

As a guess from a brief lookover, I'd say you probably need to close your input stream before attempting to write to that file.