A day with .Net

My day to day experince in .net

Archive for April, 2013

Valid DICOM file checking c#

Posted by vivekcek on April 17, 2013

Normally the extension for a DICOM file is ‘.dcm’. But this extension never guarantee the file is a valid DICOM file. So in this post i will explain how to check the file is a DICOM via pure c# code.

DICOM is a binary file, in a DICOM file first 128(0-127) bytes is unused. the next 4 bytes(128-131) contain letters ‘D’,’I’,’C’,’M’.

So our logic is to ready all bytes from 128-131 using some binary reader and equate with ‘D’,’I’,’C’,’M’



The code is given below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DICOMCheck

    public partial class Form1 : Form

        public Form1()


        private void button1_Click(object sender, EventArgs e)



            string filePath = openFileDialog1.FileName;

            BinaryReader br = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read), Encoding.ASCII);

            byte[] preamble = new byte[132];

            br.Read(preamble, 0, 132);

            if (preamble[128] != 'D' || preamble[129] != 'I' || preamble[130] != 'C' || preamble[131] != 'M')


                throw new Exception("Not a valid dicom file");



                MessageBox.Show("Valid dicom file");




Posted in c#.net, DICOM | Leave a Comment »