Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • edwich44 17 posts 93 karma points
    23 days ago
    edwich44
    0

    Updating existing media item errors - being used by another process

    Hi,

    Im trying to update existing media files on Save event. Im using a MediaSavedNotification to hook into the Save event and the following following code to update the file:-

    item.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Conventions.Media.File, item.Name, fileStream);
    

    But everytime I Save a media item via the backoffice, the following error occurs:-

    The process cannot access the file '{xxx}' because it is being used by another process

    Version: Umbraco 10.8.5

  • edwich44 17 posts 93 karma points
    22 days ago
    edwich44
    100

    I fixed the issue.

    The reason for the error was because I was trying to update a file while the file stream was still open. You need to ensure this is closed before updating the physical file.

    I achieve this by the following:-

    To close a stream either explicitly call .Close() method on the stream object OR use a "using" statement. I did the latter:-

    using (var stream = _mediaFileManager.GetFile(mediaItem, out string mediaPath))
    

    Inside this using statement, use Image.Load(stream) and store the Image object globally so you can use it outside of the using statement. Then, outside of the using statement, create a new memory stream:-

    using (var newFileStream = new MemoryStream())
    

    and use your image object and call one of the SaveAs methods (depending on the extension) and load this into newFileStream. Then call the code above using your new memory stream:-

    item.SetValue(_mediaFileManager, _mediaUrlGeneratorCollection, _shortStringHelper, _contentTypeBaseServiceProvider, Conventions.Media.File, item.Name + extension, newFileStream);
    mediaService.Save(item);
    
Please Sign in or register to post replies

Write your reply to:

Draft