Open DICOM file

Open DICOM file

The Aspose.Medical library offers a straightforward and effective method for opening and handling DICOM files within .NET applications. Opening existing DICOM files is the most common starting point for medical data workflows. After you load a DICOM file, you can get information about the file, edit the DICOM data elements, add new tags, or remove existing ones, etc.

Opening a DICOM File Using a File Path

To open an existing DICOM file, you simply have to call Aspose.Medical.Dicom.DicomFile.Open method and pass the file path (to the DICOM file you want to open) to it.

This example looks up a Shift-JIS fallback through DicomEncoding.Current.GetEncoding and opens a file. Use a fallback that matches the text bytes when the file does not declare a character set.


// Optional: tune file I/O buffers and fallback text encoding
Aspose.Medical.Dicom.Readers.ReadDicomFileOptions options = ReadDicomFileOptions.Default with
{
    FallbackEncoding = Aspose.Medical.Common.Text.DicomEncoding.Current.GetEncoding("shift_jis"),
    BufferTuningOptions = Aspose.Medical.Dicom.Readers.ReadBufferTuningOptions.Default
};

string dcmFilePath = "sample.dcm";
// Open the DICOM file using the specified file path
Aspose.Medical.Dicom.DicomFile dcm = DicomFile.Open(dcmFilePath, options);

Exceptions:

  • ArgumentException (null/whitespace path),
  • FileNotFoundException (path not found),
  • BadDicomFileException (not a valid DICOM file).

Opening a DICOM File from a Stream

To open an existing DICOM file using its System.IO.Stream, you simply have to call the Aspose.Medical.Dicom.DicomFile.Open method and pass the stream (with the DICOM file you want to open) to it.

This c# code shows you how to open a DICOM file using its stream:

// Optional: tune stream read buffers and fallback text encoding
Aspose.Medical.Dicom.Readers.ReadDicomStreamOptions options = ReadDicomStreamOptions.Default with
{
    FallbackEncoding = System.Text.Encoding.UTF8,
    BufferTuningOptions = Aspose.Medical.Dicom.Readers.ReadBufferTuningOptions.Default
};

Aspose.Medical.Dicom.Readers.ITagDataReadingStrategy strategy = TagDataReadingStrategies.ReadAll();

await using System.IO.FileStream fs = new("sample.dcm", FileMode.Open, FileAccess.Read);

Aspose.Medical.Dicom.DicomFile dcm = DicomFile.Open(fs, options, strategy);

Exception: BadDicomFileException if the stream does not contain a valid DICOM file.

Opening a DICOM File from Pipe

The synchronous Open(Pipe) overload requires each input segment to be immediately available. It does not wait for a producer. This example preloads a small file and completes the writer before parsing; use OpenAsync with concurrent production for streamed input.

This c# code shows you how to open a DICOM file using pipe:

Aspose.Medical.Dicom.Readers.ReadDicomPipeOptions options = ReadDicomPipeOptions.Default with
{
    FallbackEncoding = System.Text.Encoding.UTF8,
};

System.IO.Pipelines.Pipe pipe = new(new PipeOptions(pauseWriterThreshold: 0));
await pipe.Writer.WriteAsync(System.IO.File.ReadAllBytes("sample.dcm"));
await pipe.Writer.CompleteAsync();
try
{
    Aspose.Medical.Dicom.DicomFile dcm = DicomFile.Open(pipe, options);
    System.Console.WriteLine(dcm.Dataset.Count);
}
finally
{
    await pipe.Reader.CompleteAsync();
}

Exception: BadDicomFileException if the stream does not contain a valid DICOM file.

Opening a DICOM File from Pipe Reader

Use OpenAsync(PipeReader) when input may arrive asynchronously. The caller owns and completes the supplied reader; the library leaves it open. The following reader is backed by a file stream:

This c# code shows you how to open a DICOM file using pipe:

Aspose.Medical.Dicom.Readers.ReadDicomPipeOptions options = ReadDicomPipeOptions.Default with
{
    FallbackEncoding = Aspose.Medical.Common.Text.DicomEncoding.Current.GetEncoding("shift_jis"),
};

await using System.IO.FileStream input = File.OpenRead("sample.dcm");
System.IO.Pipelines.PipeReader pipeReader = PipeReader.Create(
    input, new StreamPipeReaderOptions(leaveOpen: true));
try
{
    Aspose.Medical.Dicom.DicomFile dcm = await DicomFile.OpenAsync(pipeReader, options);
    System.Console.WriteLine(dcm.Dataset.Count);
}
finally
{
    await pipeReader.CompleteAsync();
}

Exception: BadDicomFileException if the stream does not contain a valid DICOM file.

Buffer tuning

When opening from file/stream, you can tune the underlying buffers via ReadBufferTuningOptions on:

  • ReadDicomFileOptions.BufferTuningOptions
  • ReadDicomStreamOptions.BufferTuningOptions

ReadBufferTuningOptions allows to specify:

  • MinimumReadSize. Low-watermark in bytes before refilling. Default value is -1. Clamped to [4 KiB, 4 MiB], aligned up to 4 KiB.
  • BufferSize. Minimum buffer size (bytes) when renting from the pool. Default value is -1. Clamped to [4 KiB, 4 MiB], aligned up to 4 KiB.

For pipe inputs, the producer controls buffer sizes and flush cadence; ReadDicomPipeOptions exposes only FallbackEncoding. ReadLargeOnDemand is unsupported for Pipe and PipeReader inputs. Use ReadAll or SkipLargeTags for those sources.

Asynchronous reading and ownership

OpenAsync has file-path, stream, Pipe, and PipeReader overloads with an optional CancellationToken. Await the result before accessing its dataset. File-path overloads manage their input stream. Stream overloads leave the supplied stream open, and pipe overloads leave the supplied reader open. With deferred file or stream values, keep the original source available as described in memory management.

using System.Threading.CancellationTokenSource cancellation = new(System.TimeSpan.FromSeconds(30));
Aspose.Medical.Dicom.DicomFile dicomFile = await DicomFile.OpenAsync(
    "sample.dcm", cancellationToken: cancellation.Token);
System.Console.WriteLine(dicomFile.Dataset.Count);

Handling Character Encoding in DICOM Files

Some DICOM files may contain non-ASCII characters in their data. If the encoding is not specified in the file itself, you can provide a fallback encoding to ensure proper text interpretation.

Each input kind has a read-options type with FallbackEncoding. It supplies the initial encoding when no character set is declared. A nonempty Specific Character Set element selects its declared encodings; an unrecognized identifier resolves to the library’s default ASCII encoding. Register a custom character set when needed, as shown in text encoding.

This example looks up the Shift-JIS encoding through DicomEncoding.Current and supplies it as the fallback:

string dicomFilePath = "sample.dcm";

System.Text.Encoding fallbackEncoding = Aspose.Medical.Common.Text.DicomEncoding.Current.GetEncoding("shift_jis");

// Apply the looked-up fallback encoding.
Aspose.Medical.Dicom.Readers.ReadDicomFileOptions options = ReadDicomFileOptions.Default with
{
    FallbackEncoding = fallbackEncoding,
    BufferTuningOptions = Aspose.Medical.Dicom.Readers.ReadBufferTuningOptions.Default
};


// Open the DICOM file with fallback encoding
Aspose.Medical.Dicom.DicomFile dcm = DicomFile.Open(dicomFilePath, options);

Advanced Options

The Aspose.Medical.Dicom library offers several advanced strategies for reading data from DICOM files efficiently. This is especially useful when dealing with large datasets where memory optimization is critical. You can find additional information here.