Sanktos
Sanktos

Reputation: 59

How to recognize DICOM files? C#

I have a folder with files, but not all of them are DICOM files and I need to recognize which one is a DICOM.

My first decision was to create foreach loop where I am checking Extension:

foreach (var item in fileList.Where(x => x.Extension == ".dcm"))
        {
        }

But not all of them have ".dcm" and some of them do not, but they are DICOM.

I am using fo-dicom nuget package, but didn't find the answer there.

My question is: How to check all files for DICOM?

I know that Dicom file has 128 bytes free and then the last 4 bytes for "DICM", but how I can check this?

Upvotes: 1

Views: 1525

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109567

You can just skip the first 128 bytes of the file and read the next 4 bytes and compare them with the ASCII codes for "DICM", for example with seekable Stream:

byte[] dicomPrefix    = new byte[4];
byte[] expectedPrefix = "DICM".Select(c => (byte)c).ToArray();

using (var file = File.OpenRead("your filepath here"))
{
    // Assert.True(file.CanSeek)
    if (file.Length >= 132)
    {
        file.Position = 128; // Skip first 128 bytes.
        file.Read(dicomPrefix, 0, dicomPrefix.Length);

        if (dicomPrefix.SequenceEqual(expectedPrefix))
        {
            // It's a DICOM file.
        }
    }
}

Pay attention to:

Upvotes: 3

Sanktos
Sanktos

Reputation: 59

I think that I found a solution for my question:

foreach (FileInfo f in fileList)
{
    bool isDicom = DicomFile.HasValidHeader(f.FullName);
    if (isDicom)
    {
    }
}

Upvotes: 0

gofal3
gofal3

Reputation: 1238

If you are using fo-dicom, then you can use the built in method DicomFile.HasValidHeader(filename), that returns true or false.

this method checks for those magic bytes but also checks for older version of dicom, where the 128 bytes are not present.

Upvotes: 4

Related Questions