I know this has been answered already but I had a similar requirement, so I whipped up some extension methods to do exactly that. Works on Files, FileStreams, MemoryStreams and generic Streams. Only reads the specific 4 bytes needed to validate the filetype. Extremely efficient, I was able to run through thousands of files within seconds.
C#
public static class Dicom
{
public static bool IsDicomFile(this Stream s)
{
//Create an empty 4 byte array
byte[] dba = new byte[4];
//Seek to 0x80
s.Seek(128, SeekOrigin.Begin);
//Read the following 4 dba
s.Read(dba, 0, 4);
//Compare to 'DICM'
return dba.SequenceEqual(new byte[4] {68, 73, 67, 77});
}
public static bool IsDicomFile(this MemoryStream ms)
{
return ((Stream)ms).IsDicomFile();
}
public static bool IsDicomFile(this FileStream fs)
{
return ((Stream)fs).IsDicomFile();
}
public static bool IsDicomFile(this FileInfo fi)
{
return fi.OpenRead().IsDicomFile();
}
}
VB.NET
<Extension()> _
Public Function IsDicomFile(ByVal s As Stream) As Boolean
'Create an empty 4 byte array
Dim dba() As Byte = New Byte(3) {}
'Seek to 0x80
s.Seek(128, SeekOrigin.Begin)
'Read the subsequent 4 bytes
s.Read(dba, 0, 4)
'Compare to 'DICM'
Return dba.SequenceEqual(New Byte(3) {68, 73, 67, 77})
End Function
<Extension()> _
Public Function IsDicomFile(ByVal ms As MemoryStream) As Boolean
Return DirectCast(ms, Stream).IsDicomFile
End Function
<Extension()> _
Public Function IsDicomFile(ByVal fs As FileStream) As Boolean
Return DirectCast(fs, Stream).IsDicomFile
End Function
<Extension()> _
Public Function IsDicomFile(ByVal fi As FileInfo) As Boolean
Return fi.OpenRead().IsDicomFile
End Function