How To Delete An Image That Has Been Used In A Load Image Activity?

How to delete an image that has been used in a Load image activity?

Issue Description: After loading an image using the File Load activity and using it in other activities, consider in the end to delete it with a Delete File activity in order to free up some space memory on the Robot machine. This is currently not working as the file is blocked by a file handle.

An error received while trying this approach:

" Source: Delete File

Message: The process cannot access the file 'C:\\Users\\username\\Documents\\UiPath\\StorageBucketPDF\\image_to_be_deleted.png' because it is being used by another process.

System.IO.IOException: The process cannot access the file 'C:\\Users\\username\\Documents\\UiPath\\StorageBucketPDF\image_to_be_deleted.png' because it is being used by another process. at System.IO.FileSystem.DeleteFile(String fullPath)

at System.IO.File.Delete(String path)

at UiPath.Core.Activities.DeleteFileX.Execute(CodeActivityContext context)

at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)

at System.Activities.ActivityInstance.Execute(ActivityExecutor executor, BookmarkManager bookmarkManager)

at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)"

image.png

Root Cause: If the object is IDisposable, it is a good idea to dispose it when no longer needed, especially if the object uses unmanaged resources. When working with unmanaged resources in C# there should be a finalizer that will still release the unmanaged resources. Instead of deallocating the resources when it should be done, it will be deferred to when the garbage collector finalizes the managed object. It can still cause many other issues though (such as unreleased locks).

The .NET garbage collector does not allocate or release unmanaged memory. The pattern for disposing of an object, referred to as the dispose pattern, imposes order on the lifetime of an object. The dispose pattern is used for objects that implement the IDisposable interface, and is common when interacting with file and pipe handles, registry handles, wait handles, or pointers to blocks of unmanaged memory. This is because the garbage collector is unable to reclaim unmanaged objects.

To help ensure that resources are always cleaned up appropriately, a Dispose method should be idempotent, such that it is callable multiple times without throwing an exception. Furthermore, subsequent invocations of Dispose should do nothing.

Resolution:

  • Add before the Delete File activity an Invoke Method activity set as the below:

TargetType: (null)

TargetObject: ImageObject.UiImage

MethodName: Dispose

After performing this step, the Image object will not be locked anymore in the workflow process and it will be possible to delete it.