0

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.

Ofirster
  • 109
  • 8

1 Answers1

0

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.

Dan
  • 858
  • 7
  • 18
  • If I close the originalFileStream the following excpetion occurs: System.IO.IOException: 'Cannot read from the stream.' – Ofirster Jan 26 '18 at 19:37
  • Yeah you can't read and write into the file at the same time, perhaps you should read the bitmap into a memory stream then close the original file stream and use the memory stream to write. – Dan Jan 26 '18 at 19:43
  • What is a memory stream? How do I do that? – Ofirster Jan 26 '18 at 19:50