Image files which have been read by DicomObjects using ReadFile (COM) or Read (.NET) cannot normally be deleted (or over-written using WriteFile(COM version)/Write(.NET version) etc.) until the file is released. This is because pixel data from the files is read “as needed” (using memory mapping for COM or a duplicate FileStream for .NET). This behaviour is enabled by default, causing only the data actually needed at any time to be read into memory. This requires that the file be locked whilst the associated image object exists.

If you need to over-write or delete the file, then you can use one of the following methods to solve this problem:

Registry Method (COM and .NET)

Create/Set the “DisableMemoryMapping” registry value to “1”. This can be done in two ways:

Using the real registry (COM only)

HKEY_LOCAL_MACHINE/Software/Medical Connections/DicomObjects/DisableMemoryMapping = 1 (it’s a DWORD)

Using the internal pseudo-registry (COM and .NET)

e.g. in VB

Dim g as New DicomGlobal
g.RegWord("DisableMemoryMapping") = 1

or in C#:

DicomGlobal.SetRegWord("DisableMemoryMapping", 1);

Use “DicomImage.DecompressAll” method

This causes the whole pixel data to be read into memory (including decompression if necessary) - releasing any mapping/file handles previously associated with the image.

Dispose the image

If the image is not needed, then of course it can be released explicitly

  • In DicomObjects.NET, use the DicomImage Dispose method before attempting to delete an image file that has been read into a DicomImage object. With this approach one can delete the file yet still benefit from the advantages of memory mapping.
  • When using the COM version of DicomObjects from a .NET environment, it is important to realise that the COM object will not be released (and therefore the lock on the file not released) until the .NET garbage collection system has completed a run. To ensure that this happens, you will need the following code
[set all objects referencing the image to null]
[delete the file]

CloseFilesAfterReading property

In .NET version of Dicom Objects there are a few other methods to achieve the file release.

  1. You can set an equivalent DicomGlobal property
    DicomGlobal.CloseFilesAfterReading = true;
  2. You can modify the global default ReadBehaviours property
    DicomGlobal.DefaultReadBehaviour.CloseFilesAfterReading = true;
  3. You can control/override the behaviour for a particular read operation
    ReadBehaviours rb = new ReadBehaviours() { CloseFilesAfterReading = true };
    DicomDataSet ds = new DicomDataSet();
    ds.Read(FileName, bh);

Any of these will force the whole file to be read into memory at read time and will then release the file on the disk immediately.