Ejemplo n.º 1
0
        /// <summary>
        /// Searches for Studies in the local path, specified by the user in the <see cref="Configuration"/>,
        /// and indexed by the DICOMDIR database.
        /// Implements a local C-FIND at STUDY level command of the DICOM standard
        /// </summary>
        /// <param name="configuration">Info on the path and hierarchy used to store the DICOM files.</param>
        public static List <Study> CFINDLocalStudies(Configuration configuration)
        {
            string dicomDirPath = Path.Combine(configuration.fileDestination, "DICOMDIR");

            // prepare to receive data
            var localStudyResponses = new List <Study>();

            using (var fileStream = new FileStream(dicomDirPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                var dicomDir = DicomDirectory.Open(fileStream);
                if (dicomDir != null)
                {
                    foreach (var patientRecord in dicomDir.RootDirectoryRecordCollection)
                    {
                        foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                        {
                            studyRecord.Add(DicomTag.PatientName, patientRecord.GetSingleValue <string>(DicomTag.PatientName));
                            studyRecord.Add(DicomTag.PatientID, patientRecord.GetSingleValue <string>(DicomTag.PatientID));
                            Study myStudy = new Study(studyRecord, configuration.studyTemplate);
                            localStudyResponses.Add(myStudy);
                        }
                    }
                }
            }
            return(localStudyResponses);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Searches for the Series matching a given <see cref="Study"/>, in the local path specified by the user in the <see cref="Configuration"/>, and indexed by the DICOMDIR database.
        /// Implements a local C-FIND at SERIES level command of the DICOM standard.
        /// Implements
        /// </summary>
        /// <param name="configuration">Info on the path and hierarchy used to store the DICOM files.</param>
        public static List <Series> CFINDLocalSeries(Configuration configuration, Study study)
        {
            string dicomDirPath = Path.Combine(configuration.fileDestination, "DICOMDIR");

            // prepare to receive data
            var localSeriesResponses = new List <Series>();

            using (var fileStream = new FileStream(dicomDirPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                var dicomDir = DicomDirectory.Open(fileStream);
                if (dicomDir != null)
                {
                    foreach (var patientRecord in dicomDir.RootDirectoryRecordCollection)
                    {
                        foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                        {
                            if (studyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID) ==
                                study.getStudyInstanceUID())
                            {
                                foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                                {
                                    seriesRecord.Add(DicomTag.StudyInstanceUID,
                                                     studyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
                                    seriesRecord.Add(DicomTag.StudyDate,
                                                     studyRecord.GetSingleValue <string>(DicomTag.StudyDate));
                                    Series mySeries = new Series(seriesRecord, configuration.seriesTemplate);
                                    localSeriesResponses.Add(mySeries);
                                }
                            }
                        }
                    }
                }
            }
            return(localSeriesResponses);
        }
Ejemplo n.º 3
0
        public void AddFile_AnonymizedSeries_AllFilesAddedToSameStudySeriesNode()
        {
            var dicomFiles = GetDicomFilesFromZip(TestData.Resolve("abd1.zip"));

            // Anonymize all files
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
            }

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                var entry = dicomDir.AddFile(dicomFile);
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID), entry.InstanceRecord.GetSingleValue <string>(DicomTag.ReferencedSOPInstanceUIDInFile));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID), entry.SeriesRecord.GetSingleValue <string>(DicomTag.SeriesInstanceUID));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID), entry.StudyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
            }

            var imageNodes = dicomDir.RootDirectoryRecord.LowerLevelDirectoryRecord.LowerLevelDirectoryRecord
                             .LowerLevelDirectoryRecordCollection;

            Assert.Equal(dicomFiles.Count, imageNodes.Count());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Load a DICOMDIR
        /// </summary>
        /// <param name="filename"></param>
        public void Load(string filename)
        {
            try
            {
                _dir = new DicomDirectory(_aeTitle);

                _dir.Load(filename);


                // Show a simple traversal
                foreach (DirectoryRecordSequenceItem patientRecord in _dir.RootDirectoryRecordCollection)
                {
                    PatientRecords++;
                    foreach (DirectoryRecordSequenceItem studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                    {
                        StudyRecords++;
                        foreach (DirectoryRecordSequenceItem seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                        {
                            SeriesRecords++;
                            foreach (DirectoryRecordSequenceItem instanceRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                            {
                                InstanceRecords++;
                            }
                        }
                    }
                }

                Platform.Log(LogLevel.Info, "Loaded DICOMDIR with {0} Patient Records, {1} Study Records, {2} Series Records, and {3} Image Records",
                             PatientRecords, StudyRecords, SeriesRecords, InstanceRecords);
            }
            catch (Exception e)
            {
                Platform.Log(LogLevel.Error, e, "Unexpected exception reading DICOMDIR: {0}", filename);
            }
        }
Ejemplo n.º 5
0
        private static void ReadMedia(string fileName)
        {
            var dicomDirectory = DicomDirectory.Open(fileName);

            foreach (var patientRecord in dicomDirectory.RootDirectoryRecordCollection)
            {
                Console.WriteLine(
                    "Patient: {0} ({1})",
                    patientRecord.GetSingleValue<string>(DicomTag.PatientName),
                    patientRecord.GetSingleValue<string>(DicomTag.PatientID));

                foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                {
                    Console.WriteLine("\tStudy: {0}", studyRecord.GetSingleValue<string>(DicomTag.StudyInstanceUID));

                    foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                    {
                        Console.WriteLine("\t\tSeries: {0}", seriesRecord.GetSingleValue<string>(DicomTag.SeriesInstanceUID));

                        foreach (var imageRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                        {
                            Console.WriteLine(
                                "\t\t\tImage: {0} [{1}]",
                                imageRecord.GetSingleValue<string>(DicomTag.ReferencedSOPInstanceUIDInFile),
                                imageRecord.GetSingleValue<string>(DicomTag.ReferencedFileID));
                        }
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void AddFile_AnonymizedSeries_AllFilesAddedToDifferentPatientNodes()
        {
            var dicomFiles = GetDicomFilesFromZip(TestData.Resolve("abd1.zip"));

            // Anonymize all files
            var patname    = "Pat^Name";
            var patname2   = "Pat^^Name^^";
            var patname3   = "PAT Name";
            var patname4   = "Name^Pat";
            var anonymizer = new DicomAnonymizer();

            foreach (var dicomFile in dicomFiles)
            {
                anonymizer.AnonymizeInPlace(dicomFile);
                dicomFile.Dataset.AddOrUpdate(DicomTag.PatientName, patname);
            }
            // the name of the first image is slightly different
            dicomFiles.First().Dataset.AddOrUpdate(DicomTag.PatientName, patname2);
            dicomFiles.ElementAt(1).Dataset.AddOrUpdate(DicomTag.PatientName, patname3);
            dicomFiles.ElementAt(2).Dataset.AddOrUpdate(DicomTag.PatientName, patname4);

            // Create DICOM directory
            var dicomDir = new DicomDirectory();

            foreach (var dicomFile in dicomFiles)
            {
                var entry = dicomDir.AddFile(dicomFile);
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SOPInstanceUID), entry.InstanceRecord.GetSingleValue <string>(DicomTag.ReferencedSOPInstanceUIDInFile));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.SeriesInstanceUID), entry.SeriesRecord.GetSingleValue <string>(DicomTag.SeriesInstanceUID));
                Assert.Equal(dicomFile.Dataset.GetSingleValue <string>(DicomTag.StudyInstanceUID), entry.StudyRecord.GetSingleValue <string>(DicomTag.StudyInstanceUID));
            }

            // there shall be only one patient record
            Assert.Equal(4, dicomDir.RootDirectoryRecordCollection.Count());
        }
Ejemplo n.º 7
0
        public void Open_MediaStorageSOPInstanceUID_ShouldBeConsistent()
        {
            var dir      = DicomDirectory.Open(TestData.Resolve("DICOMDIR"));
            var expected = dir.FileMetaInfo.GetSingleValue <DicomUID>(DicomTag.MediaStorageSOPInstanceUID).UID;
            var actual   = dir.MediaStorageSOPInstanceUID.UID;

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 8
0
        public async Task OpenAsync_DicomDirFile_Succeeds()
        {
            var dir = await DicomDirectory.OpenAsync(TestData.Resolve("DICOMDIR"));

            var expected = DicomUID.MediaStorageDirectoryStorage.UID;
            var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 9
0
        public void Open_DicomDirStream_Succeeds()
        {
            using var stream = File.OpenRead(TestData.Resolve("DICOMDIR"));
            var dir = DicomDirectory.Open(stream);

            var expected = DicomUID.MediaStorageDirectoryStorage.UID;
            var actual   = dir.FileMetaInfo.MediaStorageSOPClassUID.UID;

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 10
0
        void cmd_DataSetStored(object sender, DataSetStoredEventArgs e)
        {
            if (DicomDirectory != null)
            {
                DicomDirectory.InsertDataSet(e.DataSet, e.ReferencedFileName);
            }

#if DEBUG
            Console.WriteLine(e.ReferencedFileName);
#endif
        }
Ejemplo n.º 11
0
        public void ShowDicomDirectoryMetaInformation(DicomDirectory dicomDirectory)
        {
            _log($"Dicom Directory Information:");
            var fileMetaInfo = dicomDirectory.FileMetaInfo;

            _log($"Media Storage SOP Class UID: '{fileMetaInfo.MediaStorageSOPClassUID}'");
            _log($"Media Storage SOP Instance UID: '{fileMetaInfo.MediaStorageSOPInstanceUID}'");
            _log($"Transfer Syntax: '{fileMetaInfo.TransferSyntax}'");
            _log($"Implementation Class UID: '{fileMetaInfo.ImplementationClassUID}'");
            _log($"Implementation Version Name: '{fileMetaInfo.ImplementationVersionName}'");
            _log($"Source Application Entity Title: '{fileMetaInfo.SourceApplicationEntityTitle}'");
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Scan files and write to <see cref="DicomDirectory"/>.
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static DicomDirectory WriteMedia(string path)
        {
            var dirInfo = new DirectoryInfo(path);

            var dicomDir = new DicomDirectory();

            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var dicomFile = DicomFile.Open(file.FullName);
                dicomDir.AddFile(dicomFile, string.Format(@"00001\{0}", file.Name));
            }
            return(dicomDir);
        }
Ejemplo n.º 13
0
        public void AddFile_LongFilename_WithGlobalValidationSupression()
        {
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(TestData.Resolve(filename));

            var dicomDir = new DicomDirectory()
            {
                AutoValidate = false
            };

            Assert.Null(Record.Exception(()
                                         => dicomDir.AddFile(dicomFile, filename)));
            Assert.Single(dicomDir.RootDirectoryRecordCollection);
        }
Ejemplo n.º 14
0
        static void WriteMedia(string path)
        {
            var dicomDirPath = Path.Combine("D:\\", "DICOMDIR.dcm");
            var dirInfo      = new DirectoryInfo(path);

            var dicomDir = new DicomDirectory();

            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var dicomFile = DicomFile.Open(file.FullName);
                dicomDir.AddFile(dicomFile, file.FullName);
            }
            dicomDir.Save(dicomDirPath);
        }
Ejemplo n.º 15
0
        public void AddFile_LongFilename()
        {
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(TestData.Resolve(filename));

            var dicomDir = new DicomDirectory();

            Assert.True(dicomDir.ValidateItems);
            Assert.Throws <DicomValidationException>(()
                                                     => dicomDir.AddFile(dicomFile, filename));

            dicomDir.AutoValidate = false;
            dicomDir.AddFile(dicomFile, filename);
            Assert.Single(dicomDir.RootDirectoryRecordCollection);
        }
Ejemplo n.º 16
0
        private static void WriteMedia(string path)
        {
            var dicomDirPath = Path.Combine(path, "DICOMDIR");

            var dirInfo = new DirectoryInfo(path);

            var dicomDir = new DicomDirectory();
            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var dicomFile = DicomFile.Open(file.FullName);

                dicomDir.AddFile(dicomFile, string.Format(@"000001\{0}", file.Name));
            }

            dicomDir.Save(dicomDirPath);
        }
        public void CreateDicomdirTest()
        {
            DicomFile file = new DicomFile("CreateFileTest.dcm");

            SetupMR(file.DataSet);
            SetupMetaInfo(file);

            DicomDirectory writer    = new DicomDirectory("");
            int            fileCount = 1;

            writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

            file = new DicomFile("CreateXaFileTest.dcm");
            SetupMultiframeXA(file.DataSet, 256, 256, 10);
            SetupMetaInfo(file);
            writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

            DicomFile newfile = new DicomFile("test2.dcm");

            SetupKoForImage(newfile.DataSet, file.DataSet);
            SetupMetaInfo(newfile);
            writer.AddFile(newfile, String.Format("DICOM\\FILE{0}", fileCount++));

            IList <DicomAttributeCollection> seriesList = SetupMRSeries(2, 2, DicomUid.GenerateUid().UID);

            foreach (DicomAttributeCollection collection in seriesList)
            {
                file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
                fileCount++;
                SetupMetaInfo(file);

                writer.AddFile(file, String.Format("DIR001\\FILE{0}", fileCount));
            }

            writer.FileSetId = "TestDicomdir";
            writer.Save("DICOMDIR");


            DicomDirectory reader = new DicomDirectory("");

            reader.Load("DICOMDIR");


            string failureReason;

            Assert.IsTrue(Compare(writer.RootDirectoryRecord, reader.RootDirectoryRecord, out failureReason), failureReason);
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            LogToDebugConsole("Performing Dicom directory dump:");

            try
            {
                var dicomDirectory = DicomDirectory.Open(PathToDicomDirectoryFile);

                LogToDebugConsole(dicomDirectory.WriteToString());

                LogToDebugConsole("Dicom directory dump operation was successful");
            }
            catch (Exception ex)
            {
                LogToDebugConsole($"Error occured during Dicom directory dump. Error:{ex.Message}");
            }
        }
Ejemplo n.º 19
0
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();

            dialog.Description = "请选择文件路径";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var studyDir = new DirectoryInfo(dialog.SelectedPath);
                var dicomDir = new DicomDirectory();

                foreach (var file in studyDir.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    string dicomFile = file.FullName;
                    AddFile(dicomFile);
                }
                UpdateIcon();
            }
        }
Ejemplo n.º 20
0
        private static void updateDatabase()
        {
            var    configuration   = new Configuration();
            string fileDestination = configuration.fileDestination;
            string dicomDirPath    = Path.Combine(fileDestination, "DICOMDIR");

            using (var fileStream = new FileStream(dicomDirPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                var dicomDir = new DicomDirectory();
                int i        = 0;
                foreach (string file in Directory.EnumerateFiles(fileDestination, "*.dcm*", SearchOption.AllDirectories))
                {
                    var dicomFile = DicomFile.Open(file);
                    dicomDir.AddFile(dicomFile, i.ToString()); i++;
                }
                dicomDir.Save(fileStream);
            }
        }
Ejemplo n.º 21
0
        public void Add(DicomDirectory dir)
        {
            _treeViewDicomdir.BeginUpdate();
            _treeViewDicomdir.TopNode = new TreeNode();

            TreeNode topNode = new TreeNode("DICOMDIR: " + dir.FileSetId);

            _treeViewDicomdir.Nodes.Add(topNode);

            foreach (DirectoryRecordSequenceItem patientRecord in dir.RootDirectoryRecordCollection)
            {
                TreeNode patientNode = new TreeNode(patientRecord.ToString());
                topNode.Nodes.Add(patientNode);

                AddTagNodes(patientNode, patientRecord);

                foreach (DirectoryRecordSequenceItem studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                {
                    TreeNode studyNode = new TreeNode(studyRecord.ToString());
                    patientNode.Nodes.Add(studyNode);

                    AddTagNodes(studyNode, studyRecord);

                    foreach (DirectoryRecordSequenceItem seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                    {
                        TreeNode seriesNode = new TreeNode(seriesRecord.ToString());
                        studyNode.Nodes.Add(seriesNode);

                        AddTagNodes(seriesNode, seriesRecord);

                        foreach (DirectoryRecordSequenceItem instanceRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                        {
                            TreeNode instanceNode = new TreeNode(instanceRecord.ToString());
                            seriesNode.Nodes.Add(instanceNode);

                            AddTagNodes(instanceNode, instanceRecord);
                        }
                    }
                }
            }
            _treeViewDicomdir.EndUpdate();
        }
Ejemplo n.º 22
0
		public void Add(DicomDirectory dir)
		{
			_treeViewDicomdir.BeginUpdate();
			_treeViewDicomdir.TopNode = new TreeNode();
			
			TreeNode topNode = new TreeNode("DICOMDIR: " + dir.FileSetId);

			_treeViewDicomdir.Nodes.Add( topNode);

			foreach (DirectoryRecordSequenceItem patientRecord in dir.RootDirectoryRecordCollection)
			{
				TreeNode patientNode = new TreeNode(patientRecord.ToString());
				topNode.Nodes.Add(patientNode);

				AddTagNodes(patientNode, patientRecord);

				foreach (DirectoryRecordSequenceItem studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
				{
					TreeNode studyNode = new TreeNode(studyRecord.ToString());
					patientNode.Nodes.Add(studyNode);

					AddTagNodes(studyNode, studyRecord);

					foreach (DirectoryRecordSequenceItem seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
					{
						TreeNode seriesNode = new TreeNode(seriesRecord.ToString());
						studyNode.Nodes.Add(seriesNode);

						AddTagNodes(seriesNode, seriesRecord);

						foreach (DirectoryRecordSequenceItem instanceRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
						{
							TreeNode instanceNode = new TreeNode(instanceRecord.ToString());
							seriesNode.Nodes.Add(instanceNode);

							AddTagNodes(instanceNode, instanceRecord);
						}
					}
				}
			}
			_treeViewDicomdir.EndUpdate();
		}
Ejemplo n.º 23
0
        private void CreateDirFile(string fileRootPath)
        {
            var path = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\dicomviewer";

            var dirInfo  = new DirectoryInfo(fileRootPath);
            var dicomDir = new DicomDirectory();

            foreach (var file in dirInfo.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var dicomFile = Dicom.DicomFile.Open(file.FullName);
                if (file.Length > (1024 * 10))
                {
                    dicomDir.AddFile(dicomFile, String.Format(@"DICOMOBJ\{0}", file.Name));
                }
            }

            var dicomDirPath = Path.Combine(path, "DICOMDIR");

            dicomDir.Save(dicomDirPath);
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            LogToDebugConsole("Creating Dicom directory...");

            try
            {
                //location where we will create the DICOMDIR file from the images
                var pathToOutputDicomDirectoryFile = Path.Combine(PathToDicomImages, "DICOMDIR");

                if (File.Exists(pathToOutputDicomDirectoryFile))
                {
                    LogToDebugConsole($"Dicom directory file already exists at '{pathToOutputDicomDirectoryFile}'. Deleting...");
                    File.Delete(pathToOutputDicomDirectoryFile);
                }

                var directoryInfoForDicomImagesFolder = new DirectoryInfo(PathToDicomImages);

                var dicomDir = new DicomDirectory();

                foreach (var file in directoryInfoForDicomImagesFolder.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    var dicomFile = Dicom.DicomFile.Open(file.FullName);

                    dicomDir.AddFile(dicomFile, $@"000001\{file.Name}");
                }

                dicomDir.Save(pathToOutputDicomDirectoryFile);

                LogToDebugConsole($"Dicom directory creation was successful. DICOMDIR file created at '{pathToOutputDicomDirectoryFile}'");

                var dicomDirectory = DicomDirectory.Open(pathToOutputDicomDirectoryFile);

                LogToDebugConsole("Outputing the newly created DICOM directory information to console");

                LogToDebugConsole(dicomDirectory.WriteToString());
            }
            catch (Exception ex)
            {
                LogToDebugConsole($"Error occured during Dicom directory dump. Error:{ex.Message}");
            }
        }
Ejemplo n.º 25
0
        public static DicomDirFileSet Load(string filename)
        {
            var dicomDirectory = new DicomDirectory(String.Empty);

            dicomDirectory.Load(filename);

            var directoryName = Path.GetDirectoryName(filename);

            DicomDirFileSet tmp = new DicomDirFileSet(dicomDirectory.FileSetId);

            foreach (var item in dicomDirectory.RootDirectoryRecordCollection)
            {
                if (item.DirectoryRecordType != DirectoryRecordType.Patient)
                {
                    throw new InvalidOperationException();
                }

                foreach (var subItem in item.LowerLevelDirectoryRecordCollection)
                {
                    if (subItem.DirectoryRecordType == DirectoryRecordType.Study)
                    {
                        try
                        {
                            tmp.Studies.Add(new LocalStudy(subItem, tmp, directoryName));
                        }
                        catch (Exception)
                        {
                            // TODO
                            Platform.Log(LogLevel.Warn, "invaild data when load dicom dir");
                        }
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }
            }

            return(tmp);
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            LogToDebugConsole("Performing Dicom directory dump:");

            try
            {
                var dicomDirectory = DicomDirectory.Open(PathToDicomDirectoryFile);

                var dicomDirectoryHelper = new OurDicomDirectoryHelper(LogToDebugConsole);

                dicomDirectoryHelper.ShowDicomDirectoryMetaInformation(dicomDirectory);

                foreach (var patientRecord in dicomDirectory.RootDirectoryRecordCollection)
                {
                    dicomDirectoryHelper.Display(patientRecord);

                    foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                    {
                        dicomDirectoryHelper.Display(studyRecord);

                        foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                        {
                            dicomDirectoryHelper.Display(seriesRecord);

                            foreach (var imageRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                            {
                                dicomDirectoryHelper.Display(imageRecord);
                            }
                        }
                    }
                }


                LogToDebugConsole("Dicom directory dump operation was successful");
            }
            catch (Exception ex)
            {
                LogToDebugConsole($"Error occured during Dicom directory dump. Error:{ex.Message}");
            }
        }
Ejemplo n.º 27
0
        public void AddFile_InvalidUIDInExistingFileShouldNotThrow()
        {
            // first create a file with invalid UIDs
            string filename  = "TestPattern_Palette_16.dcm";
            var    dicomFile = DicomFile.Open(TestData.Resolve(filename));

            var invalidDs = dicomFile.Dataset.NotValidated();

            invalidDs.AddOrUpdate(DicomTag.SOPInstanceUID, "1.2.4.100000.94849.4239.32.00121");
            invalidDs.AddOrUpdate(DicomTag.SeriesInstanceUID, "1.2.4.100000.94849.4239.32.00122");
            invalidDs.AddOrUpdate(DicomTag.StudyInstanceUID, "1.2.4.100000.94849.4239.32.00123");

            var invalidFile = new DicomFile(invalidDs);

            var ex = Record.Exception(() =>
            {
                var dicomDir = new DicomDirectory();
                dicomDir.AddFile(invalidFile, "FILE1");
            });

            Assert.Null(ex);
        }
Ejemplo n.º 28
0
        private static List <DicomStudy> ReadMedia(DicomDirectory dicomDirectory)
        {
            List <DicomStudy> studies = new List <DicomStudy>();

            foreach (var patientRecord in dicomDirectory.RootDirectoryRecordCollection)
            {
                var patient = ToPatient(patientRecord);

                // Get studies.
                foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                {
                    var study = ToStudy(studyRecord);
                    study.Paitent = patient;

                    // Get series.
                    foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                    {
                        var series = ToSeries(seriesRecord);

                        // Get images.
                        foreach (var imageRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                        {
                            var image = ToImage(imageRecord);
                            //       series.ImageCollection.Add(image);
                            Console.WriteLine($"Read image {image.ImageNumber}");
                        }

                        //         study.SeriesCollection.Add(series);
                    }

                    studies.Add(study);
                }
            }

            return(studies);
        }
Ejemplo n.º 29
0
		/// <summary>
		/// Load a DICOMDIR
		/// </summary>
		/// <param name="filename"></param>
		public void Load(string filename)
		{
			try
			{
				_dir = new DicomDirectory(_aeTitle);

				_dir.Load(filename);


				// Show a simple traversal
				foreach (DirectoryRecordSequenceItem patientRecord in _dir.RootDirectoryRecordCollection)
				{
					PatientRecords++;
					foreach (DirectoryRecordSequenceItem studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
					{
						StudyRecords++;
						foreach (DirectoryRecordSequenceItem seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
						{
							SeriesRecords++;
							foreach (DirectoryRecordSequenceItem instanceRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
							{
								InstanceRecords++;
							}
						}
					}
				}

				Logger.LogInfo("Loaded DICOMDIR with {0} Patient Records, {1} Study Records, {2} Series Records, and {3} Image Records",
					PatientRecords,StudyRecords,SeriesRecords,InstanceRecords);

			}
			catch (Exception e)
			{
				Logger.LogErrorException(e, "Unexpected exception reading DICOMDIR: {0}", filename);
			}
		}
Ejemplo n.º 30
0
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            int count = 0;
            int imagesToExportCount   = 0;
            InstanceCStoreCommand cmd = null;

            MatchingParameterCollection matchingParamCollection;
            MatchingParameterList       matchingParamList;

            if (this.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            ExportDicomWorkerArgs args = e.Argument as ExportDicomWorkerArgs;

            if (args == null)
            {
                throw new ArgumentException("Invalid ExportDicom argument");
            }

            if (args.CreateDicomDir)
            {
                DicomDirectory = new DicomDir(args.OutputFolder);
            }

            if (args.Anonymize)
            {
                Anonymizer.BeginBatch();
            }

            try
            {
                ViewGenerator.ViewDataRow[] exportRows = (args.Rows);

                imagesToExportCount = exportRows.Length;

                foreach (ViewGenerator.ViewDataRow exportRow in exportRows)
                {
                    try
                    {
                        string rowKeyValue;
                        string rowKeyName;
                        string viewName;

                        if (this.CancellationPending)
                        {
                            e.Cancel = true;

                            return;
                        }

                        DataRow originalRow = exportRow.OriginalRow;
                        matchingParamCollection = new MatchingParameterCollection( );
                        matchingParamList       = new MatchingParameterList( );

                        matchingParamCollection.Add(matchingParamList);

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.InstanceTableName) == 0)
                        {
                            string         sSopInstanceUid = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity imageInstance   = RegisteredEntities.GetInstanceEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Images";

                            matchingParamList.Add(imageInstance);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.SeriesTableName) == 0)
                        {
                            string         sSeriesInstanceUid = RegisteredDataRows.SeriesInfo.GetElementValue(originalRow, DicomTag.SeriesInstanceUID);
                            ICatalogEntity seriesEntity       = RegisteredEntities.GetSeriesEntity(sSeriesInstanceUid);

                            rowKeyValue = sSeriesInstanceUid;
                            rowKeyName  = "SeriesInstanceUID";
                            viewName    = "Series";

                            matchingParamList.Add(seriesEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.StudyTableName) == 0)
                        {
                            string         sStudyInstanceUid = RegisteredDataRows.StudyInfo.GetElementValue(originalRow, DicomTag.StudyInstanceUID);
                            ICatalogEntity studyEntity       = RegisteredEntities.GetStudyEntity(sStudyInstanceUid);

                            rowKeyValue = sStudyInstanceUid;
                            rowKeyName  = "StudyInstanceUID";
                            viewName    = "Studies";

                            matchingParamList.Add(studyEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.PatientTableName) == 0)
                        {
                            string         sPatientId    = RegisteredDataRows.PatientInfo.GetElementValue(originalRow, DicomTag.PatientID);
                            ICatalogEntity patientEntity = RegisteredEntities.GetPatientEntity(sPatientId);

                            rowKeyValue = sPatientId;
                            rowKeyName  = "PatientId";
                            viewName    = "Patients";

                            matchingParamList.Add(patientEntity);
                        }
                        else if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0)
                        {
                            string         sSopInstanceUid         = RegisteredDataRows.InstanceInfo.GetElementValue(originalRow, DicomTag.SOPInstanceUID);
                            ICatalogEntity hangingProtocolInstance = RegisteredEntities.GetHangingProtocolEntity(sSopInstanceUid);

                            rowKeyValue = sSopInstanceUid;
                            rowKeyName  = "SOPInstanceUID";
                            viewName    = "Hanging Protocol";

                            matchingParamList.Add(hangingProtocolInstance);
                        }
                        else
                        {
                            throw new ApplicationException("Deleted row is not a valid DICOM format.");
                        }

                        DataSet   exportDataSet = null;
                        DataRow[] rows          = null;

                        if (string.Compare(originalRow.Table.TableName, DataTableHelper.HangingProtocolTableName) == 0 && _dataAccessAgent3 != null)
                        {
                            exportDataSet = _dataAccessAgent3.QueryHangingProtocol(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.HangingProtocolTableName].Select();
                        }
                        else
                        {
                            exportDataSet = _dataAccessAgent.QueryCompositeInstances(matchingParamCollection);
                            rows          = exportDataSet.Tables[DataTableHelper.InstanceTableName].Select();
                        }

                        foreach (DataRow row in rows)
                        {
                            DicomDataSet dicomDataSet = RegisteredDataRows.InstanceInfo.LoadDicomDataSet(row);

                            if (args.Anonymize)
                            {
                                Anonymizer.Anonymize(dicomDataSet);
                            }

                            AddDicomBackgroundWorker.StoreClientSessionProxy proxy = new AddDicomBackgroundWorker.StoreClientSessionProxy();
                            proxy.AffectedSOPInstance = dicomDataSet.GetValue <string>(DicomTag.SOPInstanceUID, string.Empty);
                            proxy.AbstractClass       = dicomDataSet.GetValue <string>(DicomTag.SOPClassUID, string.Empty);


                            try
                            {
                                cmd = new InstanceCStoreCommand(proxy, dicomDataSet, _dataAccessAgent);

                                OnStoreCommandCreated(this, new StoreCommandEventArgs(cmd));

                                cmd.Configuration.DataSetStorageLocation = args.OutputFolder;
#if (LEADTOOLS_V19_OR_LATER)
                                cmd.Configuration.HangingProtocolLocation = args.OutputFolder;
#endif

                                string fileLocation = CStoreCommand.GetStorageFullPath(cmd.Configuration, dicomDataSet);
                                if (args.Overwrite || !File.Exists(fileLocation))
                                {
                                    // Only exporting, so do not validate SopInstance and do not add to database
                                    cmd.DoValidateSopInstance      = false;
                                    cmd.DoUpdateDatabase           = false;
                                    cmd.DoUseExternalStoreSettings = false;
                                    cmd.DataSetStored += cmd_DataSetStored;

                                    cmd.Execute();
                                }
                                else
                                {
                                    // File already exists -- it is not overwritten
                                    DataSetStoredEventArgs storedArgs = new DataSetStoredEventArgs(dicomDataSet, string.Empty, string.Empty, fileLocation);
                                    cmd_DataSetStored(this, storedArgs);
                                }
                            }
                            finally
                            {
                                if (cmd != null)
                                {
                                    cmd.DataSetStored -= cmd_DataSetStored;
                                }
                            }
                        }

                        count++;

                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        state.Error               = null;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.ExportedImagesCount = 1;
                        state.TotalCount          = imagesToExportCount;
                        state.RowKeyValue         = rowKeyValue;
                        state.RowKeyName          = rowKeyName;
                        state.ViewName            = viewName;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                    catch (Exception exception)
                    {
                        ExportDicomWorkerProgressState state = new ExportDicomWorkerProgressState( );

                        count++;

                        state.Error               = exception;
                        state.CurrentCount        = count;
                        state.ExportRow           = exportRow;
                        state.TotalCount          = imagesToExportCount;
                        state.ExportedImagesCount = 0;

                        ReportProgress((count * 100) / exportRows.Length, state);
                    }
                }
            }
            finally
            {
                e.Result = imagesToExportCount;
                if (DicomDirectory != null)
                {
                    DicomDirectory.Save();
                    DicomDirectory = null;
                }

                if (Anonymizer != null)
                {
                    Anonymizer.EndBatch();
                    Anonymizer = null;
                }
            }
        }
Ejemplo n.º 31
0
		public void CreateDicomdirTest()
		{
			DicomFile file = new DicomFile("CreateFileTest.dcm");

			SetupMR(file.DataSet);
			SetupMetaInfo(file);

			DicomDirectory writer = new DicomDirectory("");
			int fileCount = 1;

			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			file = new DicomFile("CreateXaFileTest.dcm");
			SetupMultiframeXA(file.DataSet, 256, 256, 10);
			SetupMetaInfo(file);
			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			DicomFile newfile = new DicomFile("test2.dcm");
			SetupKoForImage(newfile.DataSet, file.DataSet);
			SetupMetaInfo(newfile);
			writer.AddFile(newfile, String.Format("DICOM\\FILE{0}", fileCount++));

			IList<DicomAttributeCollection> seriesList = SetupMRSeries(2, 2, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				fileCount++;
				SetupMetaInfo(file);

				writer.AddFile(file, String.Format("DIR001\\FILE{0}", fileCount));
			}

			writer.FileSetId = "TestDicomdir";
			writer.Save("DICOMDIR");


			DicomDirectory reader = new DicomDirectory("");

			reader.Load("DICOMDIR");


			string failureReason;
			Assert.IsTrue(Compare(writer.RootDirectoryRecord, reader.RootDirectoryRecord, out failureReason), failureReason);
		}
Ejemplo n.º 32
0
        /// <summary>
        /// 刻录
        /// </summary>
        private void Writing()
        {
            List <IBurnMediaData> data         = new List <IBurnMediaData>();
            MediaFileSet          mediaFileSet = new MediaFileSet();

            mediaFileSet.Id = "Gold";
            List <MediaFileSetStudy> fileSetStudies = new List <MediaFileSetStudy>();
            string RootPath       = "CD";
            string studysPath     = "IMAGES";
            string studyitemPath  = "Study{0}";
            string seriesitemPath = "Series{0}";
            string filename       = "IM{0}";
            string xmlSavePath    = "studies";
            string XmlName        = "Study{0}.xml";
            int    study          = -1;
            int    series         = -1;
            int    Sopcount       = -1;

            string studyIndexName = "index.xml";

            string xmlPath = Path.Combine(this.StagingFolderPath, xmlSavePath);

            if (Directory.Exists(xmlPath))
            {
                Directory.Delete(xmlPath, true);
            }
            Directory.CreateDirectory(xmlPath);

            if (MediaWriterSettings.Default.PortablePath == null || !Directory.Exists(MediaWriterSettings.Default.PortablePath))
            {
                this.Host.ShowMessageBox("指定光盘浏览器目录不存在", MessageBoxActions.Ok);
                return;
            }
            FileDirectoryUtility.CopyFiles(MediaWriterSettings.Default.PortablePath, this.StagingFolderPath, true, true);
            RootPath = Path.Combine(this.StagingFolderPath, studysPath);
            DicomDirectory dicomDirectory = new DicomDirectory(VolumeName);

            dicomDirectory.SourceApplicationEntityTitle = VolumeName;
            dicomDirectory.FileSetId = "File Set Desc";
            try
            {
                foreach (IStudyTreeItem item in Tree.Items)
                {
                    StudyTreeItem treeitem = (StudyTreeItem)item;
                    if (!treeitem.Ischecked)
                    {
                        continue;
                    }
                    study++;
                    MediaFileSetStudy fileSet       = new MediaFileSetStudy();
                    string            tempstudypath = Path.Combine(RootPath, string.Format(studyitemPath, study));
                    StudyXml          studyXml      = new StudyXml();
                    foreach (ISeriesTreeItem seriss in treeitem.Tree.Items)
                    {
                        SeriesTreeItem seriesitem = (SeriesTreeItem)seriss;
                        if (!seriesitem.Ischecked)
                        {
                            continue;
                        }
                        series++;
                        string tempseriespath = Path.Combine(tempstudypath, string.Format(seriesitemPath, series));
                        if (Directory.Exists(tempseriespath))
                        {
                            Directory.Delete(tempseriespath, true);
                        }
                        Directory.CreateDirectory(tempseriespath);

                        foreach (var sop in seriesitem.Series.GetSopInstances())
                        {
                            if (LoadImageWorker.CancellationPending == true)
                            {
                                break;
                            }

                            if (File.Exists(sop.FilePath))
                            {
                                Sopcount++;
                                string temp = Path.Combine(tempseriespath, string.Format(filename, Sopcount));
                                File.Copy(sop.FilePath, temp);
                                int    start       = temp.IndexOf(studysPath);
                                string dirFilePath = temp.Substring(start);
                                dicomDirectory.AddFile(temp, dirFilePath);
                                string    fileName = string.Format("..\\{0}", dirFilePath);
                                DicomFile file     = new DicomFile(temp);
                                file.Load();
                                file.Filename = fileName;
                                studyXml.AddFile(file);
                                fileSet.UID = sop.StudyInstanceUid;
                            }
                        }
                    }
                    //保存studyXml
                    string xmlFileName = string.Format(XmlName, study);
                    string path        = Path.Combine(xmlPath, xmlFileName);
                    StudyXmlOutputSettings settings = new StudyXmlOutputSettings();
                    settings.IncludeSourceFileName = true;
                    XmlDocument document = studyXml.GetMemento(settings);

                    // Create an XML declaration.
                    XmlDeclaration xmldecl;
                    xmldecl          = document.CreateXmlDeclaration("1.0", null, null);
                    xmldecl.Encoding = "UTF-8";
                    document.Save(path);

                    fileSet.Value = Path.Combine(xmlSavePath, xmlFileName);;
                    fileSetStudies.Add(fileSet);
                }

                if (!Directory.Exists(RootPath))
                {
                    throw new Exception(string.Format("复制检查图像到{0}目录出错", StagingFolderPath));
                }

                IBurnMediaData info = new BurnMediaData();
                info.Type = MediaType.Dir;
                info.Path = RootPath;
                data.Add(info);

                IBurnMediaData xml = new BurnMediaData();
                xml.Path = xmlPath;
                xml.Type = MediaType.Dir;
                data.Add(xml);

                string studyindexfilename = Path.Combine(this.StagingFolderPath, studyIndexName);
                if (File.Exists(studyindexfilename))
                {
                    File.Delete(studyindexfilename);
                }
                Stream stream = File.Open(studyindexfilename, FileMode.Create);
                mediaFileSet.StudyIndex = fileSetStudies.ToArray();
                XmlSerializer serializer = new XmlSerializer(typeof(MediaFileSet));
                serializer.Serialize(stream, mediaFileSet);
                IBurnMediaData studyindex = new BurnMediaData();
                studyindex.Path = studyindexfilename;
                studyindex.Type = MediaType.File;
                data.Add(studyindex);

                string dirfilename = Path.Combine(this.StagingFolderPath, "DICOMDIR");
                dicomDirectory.Save(dirfilename);
                info      = new BurnMediaData();
                info.Type = MediaType.File;
                info.Path = dirfilename;
                data.Add(info);
                DoBurn(data);
            }
            catch (COMException ex)
            {
                this.Host.ShowMessageBox(ImapiReturnValues.GetName(ex.ErrorCode), MessageBoxActions.Ok);
            }
            catch (Exception e)
            {
                this.Host.ShowMessageBox(e.Message, MessageBoxActions.Ok);
            }
            finally
            {
                this.IsWriting = false;
            }
        }
Ejemplo n.º 33
0
        public static IEnumerable <Series> ExtractSeriesFromDicomDir(string path, bool generateMissingThumbnails)
        {
            var result = new List <DicomSeries>();

            if (!DicomFile.HasValidHeader(path))
            {
                return(result);
            }

            try
            {
                var dicomDirectory = DicomDirectory.Open(path);

                foreach (var patientRecord in dicomDirectory.RootDirectoryRecordCollection)
                {
                    foreach (var studyRecord in patientRecord.LowerLevelDirectoryRecordCollection)
                    {
                        foreach (var seriesRecord in studyRecord.LowerLevelDirectoryRecordCollection)
                        {
                            var seriesRecordType = seriesRecord.GetSingleValueOrDefault(DicomTag.DirectoryRecordType, string.Empty);
                            if (seriesRecordType != "SERIES")
                            {
                                continue;
                            }
                            var series = new DicomSeries
                            {
                                SeriesInstanceUid = seriesRecord.GetSingleValueOrDefault(DicomTag.SeriesInstanceUID, ""),
                                Number            = seriesRecord.GetSingleValueOrDefault(DicomTag.SeriesNumber, ""),
                            };

                            DicomSequence iconImageSequence;

                            if (seriesRecord.TryGetSequence(DicomTag.IconImageSequence, out iconImageSequence))
                            {
                                var iconImage = iconImageSequence.FirstOrDefault();
                                if (iconImage != null)
                                {
                                    DicomImage image = new DicomImage(iconImage);
                                    series.Thumbnail = image.RenderImage().AsWriteableBitmap();
                                }
                            }
                            foreach (var imageRecord in seriesRecord.LowerLevelDirectoryRecordCollection)
                            {
                                var imageRecordType = imageRecord.GetSingleValueOrDefault(DicomTag.DirectoryRecordType, string.Empty);
                                if (imageRecordType != "IMAGE")
                                {
                                    continue;
                                }

                                var values       = imageRecord.GetValues <string>(DicomTag.ReferencedFileID);
                                var relativePath = string.Join(@"\", values);

                                series.SopClassUid     = imageRecord.GetSingleValueOrDefault(DicomTag.ReferencedSOPClassUIDInFile, "");
                                series.NumberOfImages += Math.Max(1, imageRecord.GetSingleValueOrDefault(DicomTag.NumberOfFrames, 1));
                                var absolutePath = Path.GetDirectoryName(path) + @"\\" + relativePath;
                                series.FileNames.Add(absolutePath);
                            }

                            if (generateMissingThumbnails && series.Thumbnail == null && series.FileNames.Count > 0)
                            {
                                GenerateThumbnail(series);
                            }
                            if (series.NumberOfImages > 0)
                            {
                                result.Add(series);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.LogWarning(e, $"Could not read DICOMDIR file '{e.Message}' {e.StackTrace}");
            }
            return(result);
        }
Ejemplo n.º 34
0
		public void ComparisonTest()
		{
			DicomDirectory writer = new DicomDirectory("DICOMDIR");

			int fileCount = 1;

			DicomFile file = new DicomFile("CreateFileTest.dcm");
			SetupMR(file.DataSet);
			SetupMetaInfo(file);
			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			file = new DicomFile("CreateFileTest.dcm");
			SetupMR(file.DataSet);
			SetupMetaInfo(file);
			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			DicomFile newfile = new DicomFile("test2.dcm");
			SetupKoForImage(newfile.DataSet, file.DataSet);
			SetupMetaInfo(newfile);
			writer.AddFile(newfile, String.Format("DICOM\\FILE{0}", fileCount++));

			file = new DicomFile("CreateXaFileTest.dcm");
			SetupMultiframeXA(file.DataSet, 128, 128, 4);
			SetupMetaInfo(file);
			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			newfile = new DicomFile("test2.dcm");
			SetupKoForImage(newfile.DataSet, file.DataSet);
			SetupMetaInfo(newfile);
			writer.AddFile(newfile, String.Format("DICOM\\FILE{0}", fileCount++));


			file = new DicomFile("CreateXaFileTest.dcm");
			SetupMultiframeXA(file.DataSet, 64, 64, 4);
			SetupMetaInfo(file);
			writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

			newfile = new DicomFile("test2.dcm");
			SetupKoForImage(newfile.DataSet, file.DataSet);
			SetupMetaInfo(newfile);
			writer.AddFile(newfile, String.Format("DICOM\\FILE{0}", fileCount++));

			IList<DicomAttributeCollection> seriesList = SetupMRSeries(3, 1, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));
			}

			seriesList = SetupMRSeries(4, 4, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

				file = new DicomFile("test2.dcm");
				SetupKoForImage(file.DataSet, collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));
			}

			seriesList = SetupMRSeries(10, 1, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

				file = new DicomFile("test2.dcm");
				SetupKoForImage(file.DataSet, collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));
			}

			seriesList = SetupMRSeries(4, 3, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				SetupMetaInfo(file);
				writer.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));
			}

			writer.FileSetId = "TestDicomdir";
			writer.Save("DICOMDIR");


			DicomDirectory reader = new DicomDirectory("DICOMDIR");
			reader.Load("DICOMDIR");


			string failureReason;
			Assert.IsTrue(Compare(writer.RootDirectoryRecord, reader.RootDirectoryRecord, out failureReason), failureReason);

			// Test Append
			// Add a few more files to the file read in, then rewrite and read and compare
			seriesList = SetupMRSeries(4, 4, DicomUid.GenerateUid().UID);
			foreach (DicomAttributeCollection collection in seriesList)
			{
				file = new DicomFile("test.dcm", new DicomAttributeCollection(), collection);
				SetupMetaInfo(file);
				reader.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));

				file = new DicomFile("test2.dcm");
				SetupKoForImage(file.DataSet, collection);
				SetupMetaInfo(file);
				reader.AddFile(file, String.Format("DICOM\\FILE{0}", fileCount++));
			}

			reader.FileSetId = "TestDicomdir";
			reader.Save("DICOMDIR");


			DicomDirectory reader2 = new DicomDirectory("DICOMDIR");
			reader2.Load("DICOMDIR");


			Assert.IsTrue(Compare(reader.RootDirectoryRecord, reader2.RootDirectoryRecord, out failureReason), failureReason);
		}