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?
CodePudding user response:
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.
CodePudding user response:
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:
byte[] dicomPrefix = new byte[4];
byte[] expectedPrefix = "DICM".Select(c => (byte)c).ToArray();
using (var file = File.OpenRead("your filepath here"))
{
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.
}
}
}
CodePudding user response:
I think that I found a solution for my question:
foreach (FileInfo f in fileList)
{
bool isDicom = DicomFile.HasValidHeader(f.FullName);
if (isDicom)
{
}
}