/// <summary> /// Burns data files to disc in a single session using files from a /// single directory tree. /// </summary> /// <param name="recorder">Burning Device. Must be initialized.</param> /// <param name="path">Directory of files to burn.</param> public void BurnDirectory(IDiscRecorder2 recorder, String path) { // Define the new disc format and set the recorder IDiscFormat2Data dataWriterImage = new MsftDiscFormat2Data(); dataWriterImage.Recorder = recorder; if(!dataWriterImage.IsRecorderSupported(recorder)) { Console.WriteLine("The recorder is not supported"); return; } if (!dataWriterImage.IsCurrentMediaSupported(recorder)) { Console.WriteLine("The current media is not supported"); return; } dataWriterImage.ClientName = "IMAPI Sample"; // Create an image stream for a specified directory. // Create a new file system image and retrieve the root directory IFileSystemImage fsi = new MsftFileSystemImage(); // Set the media size fsi.FreeMediaBlocks = dataWriterImage.FreeSectorsOnMedia; // Use legacy ISO 9660 Format fsi.FileSystemsToCreate = FsiFileSystems.FsiFileSystemISO9660; // Add the directory to the disc file system IFsiDirectoryItem dir = fsi.Root; dir.AddTree(path, false); // Create an image from the file system Console.WriteLine("Writing content to disc..."); IFileSystemImageResult result = fsi.CreateResultImage(); // Data stream sent to the burning device IStream stream = result.ImageStream; DiscFormat2Data_Events progress = dataWriterImage as DiscFormat2Data_Events; progress.Update += new DiscFormat2Data_EventsHandler(DiscFormat2Data_ProgressUpdate); // Write the image stream to disc using the specified recorder. dataWriterImage.Write(stream); // Burn the stream to disc progress.Update -= new DiscFormat2Data_EventsHandler(DiscFormat2Data_ProgressUpdate); Console.WriteLine("----- Finished writing content -----"); }
public void LoadRecorder() { if (_recorders.SelectedIndex == -1) throw new InvalidOperationException("No DiscRecorder selected from the DiscRecorders list."); MsftDiscRecorder2 recorder = null; IDiscFormat2Data discFormatData = null; try { recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(_recorders.SelectedItem.InternalUniqueId); discFormatData = new MsftDiscFormat2Data(); switch (discFormatData.IsRecorderSupported(recorder)) { case 0x80004003: throw new RecorderNotSupportedException("Pointer is not valid."); case 0xC0AA0202: throw new RecorderNotSupportedException("The selected recorder is not supported on this system."); } _recorderLoaded = true; _mediaLoaded = false; } finally { if (discFormatData != null) Marshal.ReleaseComObject(discFormatData); if (recorder != null) Marshal.ReleaseComObject(recorder); } }
/// <summary> /// Examines and reports the media characteristics. /// </summary> /// <param name="recorder">Burning Device. Must be initialized.</param> public void DisplayMediaCharacteristics(IDiscRecorder2 recorder) { // Define the new disc format and set the recorder IDiscFormat2Data mediaImage = new MsftDiscFormat2Data(); mediaImage.Recorder = recorder; // *** Validation methods inherited from IMAPI2.MsftDiscFormat2 bool boolResult = mediaImage.IsRecorderSupported(recorder); if (boolResult) { Console.WriteLine("--- Current recorder IS supported. ---"); } else { Console.WriteLine("--- Current recorder IS NOT supported. ---"); } boolResult = mediaImage.IsCurrentMediaSupported(recorder); if (boolResult) { Console.WriteLine("--- Current media IS supported. ---"); } else { Console.WriteLine("--- Current media IS NOT supported. ---"); } Console.WriteLine("ClientName = {0}", mediaImage.ClientName); // Check a few CurrentMediaStatus possibilities. Each status is associated // with a bit and some combinations are legal. uint curMediaStatus = (uint)mediaImage.CurrentMediaStatus; Console.WriteLine("Checking Current Media Status"); if (curMediaStatus == (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_UNKNOWN) { Console.WriteLine("\tMedia state is unknown."); } else { if ((curMediaStatus & (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_OVERWRITE_ONLY) != 0) { Console.WriteLine("\tCurrently, only overwriting is supported."); } if ((curMediaStatus & (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_RANDOMLY_WRITABLE) != 0) { Console.WriteLine("\tCurrently, media supports random writing."); } if ((curMediaStatus & (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_APPENDABLE) != 0) { Console.WriteLine("\tMedia is currently appendable."); } if ((curMediaStatus & (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_FINAL_SESSION) != 0) { Console.WriteLine("\tMedia is in final writing session."); } if ((curMediaStatus & (uint)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_DAMAGED) != 0) { Console.WriteLine("\tMedia is damaged."); } } IMAPI_MEDIA_PHYSICAL_TYPE mediaType = mediaImage.CurrentPhysicalMediaType; Console.Write("Current Media Type"); DisplayMediaType(mediaType); Console.WriteLine("SupportedMediaTypes in the device: "); foreach (IMAPI_MEDIA_PHYSICAL_TYPE supportedMediaType in mediaImage.SupportedMediaTypes) { DisplayMediaType(supportedMediaType); } Console.Write("\n----- Finished -----"); }
private int DoBurn(string activeDiscRecorder, IMAPI_BURN_VERIFICATION_LEVEL verificationLevel) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormatData = null; int result = 0; try { discRecorder = new MsftDiscRecorder2(); discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId); discFormatData = new MsftDiscFormat2Data { Recorder = discRecorder, ClientName = "ClientName", ForceMediaToBeClosed = closeMedia }; var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = verificationLevel; object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) multisessionInterfaces = discFormatData.MultisessionInterfaces; IStream fileSystem; if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem)) return -1; discFormatData.Update += discFormatData_Update; try { discFormatData.Write(fileSystem); result = 0; } catch (COMException ex) { result = ex.ErrorCode; MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed", MessageBoxButton.OK, MessageBoxImage.Stop); } finally { if (fileSystem != null) Marshal.FinalReleaseComObject(fileSystem); } discFormatData.Update -= discFormatData_Update; if (ejectMedia) discRecorder.EjectMedia(); } catch (COMException exception) { MessageBox.Show(exception.Message); result = exception.ErrorCode; } finally { if (discRecorder != null) Marshal.ReleaseComObject(discRecorder); if (discFormatData != null) Marshal.ReleaseComObject(discFormatData); } return result; }
private void buttonDetectMedia_Click(object sender, EventArgs e) { if (devicesComboBox.SelectedIndex == -1) { return; } var discRecorder = (IDiscRecorder2)devicesComboBox.Items[devicesComboBox.SelectedIndex]; MsftFileSystemImage fileSystemImage = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder)) { labelMediaType.Text = "Media not supported!"; _totalDiscSize = 0; return; } else { // // Get the media type in the recorder // discFormatData.Recorder = discRecorder; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = discFormatData.CurrentPhysicalMediaType; labelMediaType.Text = GetMediaTypeString(mediaType); // // Create a file system and select the media type // fileSystemImage = new MsftFileSystemImage(); fileSystemImage.ChooseImageDefaultsForMediaType(mediaType); // // See if there are other recorded sessions on the disc // if (!discFormatData.MediaHeuristicallyBlank) { fileSystemImage.MultisessionInterfaces = discFormatData.MultisessionInterfaces; fileSystemImage.ImportFileSystem(); } Int64 freeMediaBlocks = fileSystemImage.FreeMediaBlocks; _totalDiscSize = 2048 * freeMediaBlocks; } } catch (COMException exception) { MessageBox.Show(this, exception.Message, "Detect Media Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } if (fileSystemImage != null) { Marshal.ReleaseComObject(fileSystemImage); } } UpdateCapacity(); }
/// <summary> /// Initializes the drive. Detects available DVD drives and the media inserted in each drive. /// </summary> /// <returns>The result of the detection.</returns> public override DriveStatus Initialize() { DriveStatus result = DriveStatus.NoDrive; try { MsftDiscMaster2 discMaster = new MsftDiscMaster2(); if (!discMaster.IsSupportedEnvironment || discMaster.Count <= 0) { result = DriveStatus.NoDrive; } else { bool possibleDriveFound = false; foreach (string recorderID in discMaster) { try { MsftDiscRecorder2 discRecorder2 = new MsftDiscRecorder2(); discRecorder2.InitializeDiscRecorder(recorderID); // Check that the drive is supported bool supportsBurn = false; foreach (IMAPI_FEATURE_PAGE_TYPE type in discRecorder2.SupportedFeaturePages) { switch (type) { case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_RANDOMLY_WRITABLE: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_INCREMENTAL_STREAMING_WRITABLE: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_WRITE_ONCE: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_DVD_DASH_WRITE: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_LAYER_JUMP_RECORDING: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_BD_WRITE: case IMAPI_FEATURE_PAGE_TYPE.IMAPI_FEATURE_PAGE_TYPE_HD_DVD_WRITE: supportsBurn = true; break; } if (supportsBurn) { break; } } // This device does not support buring, skip it. if (!supportsBurn) { continue; } MsftDiscFormat2Data discFormatData = new MsftDiscFormat2Data(); if (!String.IsNullOrEmpty(discRecorder2.ExclusiveAccessOwner)) { result = DriveStatus.DriveNotReady; } else if (discFormatData.IsCurrentMediaSupported(discRecorder2)) { discFormatData.Recorder = discRecorder2; // Detect the media if (!discFormatData.MediaHeuristicallyBlank) { result = DriveStatus.MediaNotBlank; } else if (2048L * discFormatData.TotalSectorsOnMedia < this.ImageReader.ImageFile.Length) { if (!possibleDriveFound) { result = DriveStatus.MediaTooSmall; } } else { // Valid media found, use this drive. result = this.SetActiveDrive(recorderID); // Set the write speed SetWriteSpeed(discFormatData); break; } } else if (!possibleDriveFound) { // Check if the media has files on it since IsCurrentMediaSupported returns false when the media is not recordable. DriveInfo info = new DriveInfo((string)discRecorder2.VolumePathNames[0]); if (!info.IsReady) { result = DriveStatus.NoMedia; } else if (info.RootDirectory.GetFiles().Length > 0 || info.RootDirectory.GetDirectories().Length > 0) { result = DriveStatus.MediaNotBlank; } } // If we found a drive with media, save that as a possible drive, but keep // looking in case there is a drive with valid media. possibleDriveFound = result != DriveStatus.NoDrive && result != DriveStatus.NoMedia; } catch (COMException ex) { switch ((uint)ex.ErrorCode) { case 0xC0AA0205: // E_IMAPI_RECORDER_MEDIA_BECOMING_READY case 0xC0AA0206: // E_IMAPI_RECORDER_MEDIA_FORMAT_IN_PROGRESS case 0xC0AA0207: // E_IMAPI_RECORDER_MEDIA_BUSY case 0xC0AA020D: // E_IMAPI_RECORDER_COMMAND_TIMEOUT case 0xC0AA0210: // E_IMAPI_RECORDER_LOCKED result = DriveStatus.DriveNotReady; break; default: result = DriveStatus.InvalidMedia; this.Logging.WriteException("Error trying to read media.", ex); break; } } } } } catch (COMException ex) { result = DriveStatus.NoDrive; this.Logging.WriteException("Error trying to read drives.", ex); } return result; }
/// <summary> /// The thread that does the burning of the media /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscRecorder2 object // discRecorder = new MsftDiscRecorder2(); var burnData = (BurnData)e.Argument; discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId); // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data { Recorder = discRecorder, ClientName = ClientName, ForceMediaToBeClosed = _closeMedia }; // // Set the verification level // var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = _verificationLevel; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) { multisessionInterfaces = discFormatData.MultisessionInterfaces; } // // Create the file system // IStream fileSystem; if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem)) { e.Result = -1; return; } // // add the Update event handler // discFormatData.Update += discFormatData_Update; // // Write the data here // try { discFormatData.Write(fileSystem); e.Result = 0; } catch (COMException ex) { e.Result = ex.ErrorCode; MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { if (fileSystem != null) { Marshal.FinalReleaseComObject(fileSystem); } } // // remove the Update event handler // discFormatData.Update -= discFormatData_Update; if (_ejectMedia) { discRecorder.EjectMedia(); } } catch (COMException exception) { // // If anything happens during the format, show the message // MessageBox.Show(exception.Message); e.Result = exception.ErrorCode; } finally { if (discRecorder != null) { Marshal.ReleaseComObject(discRecorder); } if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
public long GetTotalDiscSizeOFCurrentMedia(int index) { var discRecorder = devicesList[index]; MsftFileSystemImage fileSystemImage = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder)) { return(0); } else { // // Get the media type in the recorder // discFormatData.Recorder = discRecorder; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = discFormatData.CurrentPhysicalMediaType; // // Create a file system and select the media type // fileSystemImage = new MsftFileSystemImage(); fileSystemImage.ChooseImageDefaultsForMediaType(mediaType); // // See if there are other recorded sessions on the disc // if (!discFormatData.MediaHeuristicallyBlank) { fileSystemImage.MultisessionInterfaces = discFormatData.MultisessionInterfaces; fileSystemImage.ImportFileSystem(); } long freeMediaBlocks = fileSystemImage.FreeMediaBlocks; return(2048 * freeMediaBlocks); } } catch (COMException) { return(0); } finally { if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } if (fileSystemImage != null) { Marshal.ReleaseComObject(fileSystemImage); } } }
private void DetectMedia() { MsftFileSystemImage fileSystemImage = null; MsftDiscFormat2Data discFormatData = null; try { discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder)) { MediaTypeText = "Media not supported!"; totalDiscSize = 0; return; } else { // Get the media type in the recorder discFormatData.Recorder = discRecorder; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = discFormatData.CurrentPhysicalMediaType; MediaTypeText = StringProvider.GetMediaTypeString(mediaType); fileSystemImage = new MsftFileSystemImage(); fileSystemImage.ChooseImageDefaultsForMediaType(mediaType); // See if there are other recorded sessions on the disc if (!discFormatData.MediaHeuristicallyBlank) { fileSystemImage.MultisessionInterfaces = discFormatData.MultisessionInterfaces; fileSystemImage.ImportFileSystem(); } Int64 freeMediaBlocks = fileSystemImage.FreeMediaBlocks; totalDiscSize = 2048 * freeMediaBlocks; } } catch (COMException exception) { MessageBox.Show(exception.Message, "Detect Media Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (discFormatData != null) Marshal.ReleaseComObject(discFormatData); if (fileSystemImage != null) Marshal.ReleaseComObject(fileSystemImage); } UpdateCapacity(); }
/// <summary> /// Get the media type for a device path using the Aaru libraries /// </summary> /// <param name="devicePath">Path to the device</param> /// <param name="internalDriveType">Current internal drive type</param> /// <returns>MediaType, null on error</returns> private static (MediaType?, string) GetMediaType(string devicePath, InternalDriveType?internalDriveType) { char driveLetter = devicePath == null || !devicePath.Any() ? '\0' : devicePath[0]; // Take care of the non-optical stuff first // TODO: See if any of these can be more granular, like Optical is if (internalDriveType == Data.InternalDriveType.Floppy) { return(MediaType.FloppyDisk, null); } else if (internalDriveType == Data.InternalDriveType.HardDisk) { return(MediaType.HardDisk, null); } else if (internalDriveType == Data.InternalDriveType.Removable) { return(MediaType.FlashDrive, null); } // Get the current drive information string deviceId = null; bool loaded = false; try { // Get the device ID first var searcher = new ManagementObjectSearcher( "root\\CIMV2", $"SELECT * FROM Win32_CDROMDrive WHERE Id = '{driveLetter}:\'"); foreach (ManagementObject queryObj in searcher.Get()) { deviceId = (string)queryObj["DeviceID"]; loaded = (bool)queryObj["MediaLoaded"]; } // If we got no valid device, we don't care and just return if (deviceId == null) { return(null, "Device could not be found"); } else if (!loaded) { return(null, "Device is not reporting media loaded"); } MsftDiscMaster2 discMaster = new MsftDiscMaster2(); deviceId = deviceId.ToLower().Replace('\\', '#').Replace('/', '#'); string id = null; foreach (var disc in discMaster) { if (disc.ToString().Contains(deviceId)) { id = disc.ToString(); } } // If we couldn't find the drive, we don't care and return if (id == null) { return(null, "Device ID could not be found"); } // Create the required objects for reading from the drive MsftDiscRecorder2 recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(id); MsftDiscFormat2Data dataWriter = new MsftDiscFormat2Data(); // If the recorder is not supported, just return if (!dataWriter.IsRecorderSupported(recorder)) { return(null, "IMAPI2 recorder not supported"); } // Otherwise, set the recorder to get information from dataWriter.Recorder = recorder; var media = dataWriter.CurrentPhysicalMediaType; return(media.IMAPIToMediaType(), null); } catch (Exception ex) { return(null, ex.Message); } }
/// <summary> /// 刻录 /// </summary> public void Burn(string diskName = "SinoUnion") { if (!CanBurn) { throw new Exception("当前磁盘状态不支持刻录"); } if (string.IsNullOrEmpty(diskName)) { throw new Exception("DiskName不能为空"); } if (BurnMediaList.Count <= 0) { throw new Exception("待刻录文件列表不能为空"); } if (BurnMediaFileSize <= 0) { throw new Exception("待刻录文件大小为0"); } try { //说明 //1.fsi.ChooseImageDefaults用的是IMAPI2FS的,我们定义的msRecorder是IMAPI2的.所以必须用动态类型 //2.dataWriter也要使用动态类型,要不然Update事件会出异常. // Create an image stream for a specified directory. dynamic fsi = new IMAPI2FS.MsftFileSystemImage(); // Disc file system IMAPI2FS.IFsiDirectoryItem dir = fsi.Root; // Root directory of the disc file system dynamic dataWriter = new MsftDiscFormat2Data(); //Create the new disc format and set the recorder dataWriter.Recorder = msRecorder; dataWriter.ClientName = "SinoGram"; //不知道这方法不用行不行.用的参数是IMAPI2FS的. //所以学官网的例子,把fsi改成了动态的.使用msRecorder作为参数 fsi.ChooseImageDefaults(msRecorder); //设置相关信息 fsi.VolumeName = diskName; //刻录磁盘名称 for (int i = 0; i < BurnMediaList.Count; i++) { dir.AddTree(BurnMediaList[i].MediaPath, true); } // Create an image from the file system IStream stream = fsi.CreateResultImage().ImageStream; try { dataWriter.Update += new DDiscFormat2DataEvents_UpdateEventHandler(BurnProgressChanged); dataWriter.Write(stream);// Write stream to disc } catch (System.Exception ex) { throw ex; } finally { if (stream != null) { Marshal.FinalReleaseComObject(stream); } } } catch (Exception ex) { Console.WriteLine($"刻录失败:{ex.Message}"); } }
public Int64 detectDisk(IDiscRecorder2 disk) { int error_code = 0; var discRecorder = disk; MsftFileSystemImage fileSystemImage = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder)) { //labelMediaType.Text = "Media not supported!"; MessageBox.Show("Media not supported!"); _totalDiscSize = 0; error_code = ERROR_MEDIA_NOT_SUPPORT; } else { // // Get the media type in the recorder // discFormatData.Recorder = discRecorder; IMAPI_MEDIA_PHYSICAL_TYPE mediaType = discFormatData.CurrentPhysicalMediaType; //labelMediaType.Text = GetMediaTypeString(mediaType); // // Create a file system and select the media type // fileSystemImage = new MsftFileSystemImage(); fileSystemImage.ChooseImageDefaultsForMediaType(mediaType); // // See if there are other recorded sessions on the disc // if (!discFormatData.MediaHeuristicallyBlank) { fileSystemImage.MultisessionInterfaces = discFormatData.MultisessionInterfaces; fileSystemImage.ImportFileSystem(); } Int64 freeMediaBlocks = fileSystemImage.FreeMediaBlocks; _totalDiscSize = 2048 * freeMediaBlocks; MessageBox.Show("Disk size: " + _totalDiscSize.ToString()); } } catch (COMException exception) { MessageBox.Show(exception.Message, "Detect Media Error", MessageBoxButtons.OK, MessageBoxIcon.Error); error_code = ERROR_DETECT_MEDIA; } finally { if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } if (fileSystemImage != null) { Marshal.ReleaseComObject(fileSystemImage); } } if (error_code != 0) { return(error_code); } return(_totalDiscSize); }
public void WriteImage(BurnVerificationLevel verification, bool finalize, bool eject) { if (!_recorderLoaded) throw new InvalidOperationException("LoadMedia must be called first."); MsftDiscRecorder2 recorder = null; MsftDiscFormat2Data discFormatData = null; try { recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(_recorders.SelectedItem.InternalUniqueId); discFormatData = new MsftDiscFormat2Data { Recorder = recorder, ClientName = ClientName, ForceMediaToBeClosed = finalize }; // // Set the verification level // var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = IMAPI_BURN_VERIFICATION_LEVEL.IMAPI_BURN_VERIFICATION_NONE; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) multisessionInterfaces = discFormatData.MultisessionInterfaces; // // Create the file system // IStream fileSystem; _CreateImage(recorder, multisessionInterfaces, out fileSystem); discFormatData.Update += _discFormatWrite_Update; // // Write the data // try { discFormatData.Write(fileSystem); } finally { if (fileSystem != null) Marshal.FinalReleaseComObject(fileSystem); } discFormatData.Update -= _discFormatWrite_Update; if (eject) recorder.EjectMedia(); } finally { _isWriting = false; if (discFormatData != null) Marshal.ReleaseComObject(discFormatData); if (recorder != null) Marshal.ReleaseComObject(recorder); } }
public void LoadMedia() { long mediaStateFlags; var mediaStates = new List <MediaState>(); if (!_recorderLoaded) { throw new InvalidOperationException("LoadRecorder must be called first."); } if (_recorders.SelectedIndex == -1) { throw new InvalidOperationException("No DiscRecorder selected on the DiscRecorders list."); } MsftDiscRecorder2 recorder = null; MsftFileSystemImage image = null; MsftDiscFormat2Data format = null; try { recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(_recorders.SelectedItem.InternalUniqueId); format = new MsftDiscFormat2Data(); if (!format.IsCurrentMediaSupported(recorder)) { throw new MediaNotSupportedException("There is no media in the device."); } // // Get the media type in the recorder // format.Recorder = recorder; _media = (PhysicalMedia)format.CurrentPhysicalMediaType; mediaStateFlags = (long)format.CurrentMediaStatus; foreach (MediaState state in Enum.GetValues(typeof(MediaState))) { if (((long)mediaStateFlags & (long)state) > 0) { mediaStates.Add(state); } } if (mediaStates.Count == 0) { mediaStates.Add(MediaState.Unknown); } _mediaStates = new ReadOnlyCollection <MediaState>(mediaStates); if ((mediaStateFlags & (long)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_WRITE_PROTECTED) > 0) { throw new MediaNotSupportedException("The media in the device is write protected."); } // // Create a file system and select the media type // image = new MsftFileSystemImage(); image.ChooseImageDefaultsForMediaType((IMAPI_MEDIA_PHYSICAL_TYPE)_media); // // See if there are other recorded sessions on the disc // if (!format.MediaHeuristicallyBlank) { image.MultisessionInterfaces = format.MultisessionInterfaces; image.ImportFileSystem(); } _mediaCapacity = 2048 * image.FreeMediaBlocks; _mediaLoaded = true; } finally { if (image != null) { Marshal.ReleaseComObject(image); } if (format != null) { Marshal.ReleaseComObject(format); } if (recorder != null) { Marshal.ReleaseComObject(recorder); } } }
public void WriteImage(BurnVerificationLevel verification, bool finalize, bool eject) { if (!_recorderLoaded) { throw new InvalidOperationException("LoadMedia must be called first."); } MsftDiscRecorder2 recorder = null; MsftDiscFormat2Data discFormatData = null; try { recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(_recorders.SelectedItem.InternalUniqueId); discFormatData = new MsftDiscFormat2Data { Recorder = recorder, ClientName = ClientName, ForceMediaToBeClosed = finalize }; // // Set the verification level // var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = IMAPI_BURN_VERIFICATION_LEVEL.IMAPI_BURN_VERIFICATION_NONE; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) { multisessionInterfaces = discFormatData.MultisessionInterfaces; } // // Create the file system // IStream fileSystem; _CreateImage(recorder, multisessionInterfaces, out fileSystem); discFormatData.Update += _discFormatWrite_Update; // // Write the data // try { discFormatData.Write(fileSystem); } finally { if (fileSystem != null) { Marshal.FinalReleaseComObject(fileSystem); } } discFormatData.Update -= _discFormatWrite_Update; if (eject) { recorder.EjectMedia(); } } finally { _isWriting = false; if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } if (recorder != null) { Marshal.ReleaseComObject(recorder); } } }
private string GetSupportedMediaTypes() { if (discRecorder == null) return null; // Verify recorder is supported IDiscFormat2Data discFormatData = null; try { discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsRecorderSupported(discRecorder)) return "Recorder not supported"; var supportedMediaTypes = new StringBuilder(); foreach (IMAPI_PROFILE_TYPE profileType in discRecorder.SupportedProfiles) { string profileName = StringProvider.GetProfileTypeString(profileType); if (string.IsNullOrEmpty(profileName)) continue; if (supportedMediaTypes.Length > 0) supportedMediaTypes.Append(", "); supportedMediaTypes.Append(profileName); } return supportedMediaTypes.ToString(); } catch (COMException) { return "Error getting supported types"; } finally { if (discFormatData != null) Marshal.ReleaseComObject(discFormatData); } }
public int WriteStream(System.Runtime.InteropServices.ComTypes.IStream stream, string initburner, string clientName, bool forceMediaToBeClosed, int speed, bool eject) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormat = null; var result = -1; try { discRecorder = new MsftDiscRecorder2(); discRecorder.InitializeDiscRecorder(initburner); discFormat = new MsftDiscFormat2Data(); //remove the comment for next 2 lines discFormat.Recorder = discRecorder; discRecorder.AcquireExclusiveAccess(true, clientName); //rec.DisableMcn(); // // initialize the IDiscFormat2Data // discFormat.ClientName = clientName; discFormat.ForceMediaToBeClosed = forceMediaToBeClosed; // // add the Update event handler // discFormat.Update += DiscFormatData_Update; //this is how it worked for my burner //speed = 0 => minimum speed descriptor in update // 0 < speed < minimum speed descriptor => half of minimum speed descriptor in update // minimum speed descriptor <= speed < next speed descriptor => minimum speed descriptor in update // next speed descriptor <= speed => next speed descriptorin update //discFormat.SetWriteSpeed(2000, true);//????????????? discFormat.SetWriteSpeed(speed, true); //write the stream discFormat.Write(stream); if (_backgroundWorker.CancellationPending) { return(1); } if (eject) { //wait to flush all the content on the media var state = IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_UNKNOWN; while (state == IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_UNKNOWN && !_backgroundWorker.CancellationPending) { try { state = discFormat.CurrentMediaStatus; } catch (Exception) { state = IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_UNKNOWN; Thread.Sleep(3000); } } if (!_backgroundWorker.CancellationPending) { discRecorder.EjectMedia(); } } result = 0; } finally { if (_backgroundWorker.CancellationPending) { result = 1; } if (discFormat != null) { // remove the Update event handler // discFormat.Update -= DiscFormatData_Update; Marshal.FinalReleaseComObject(discFormat); } if (discRecorder != null) { //discRecorder.EnableMcn(); discRecorder.ReleaseExclusiveAccess(); Marshal.FinalReleaseComObject(discRecorder); } } return(result); }
/// <summary> /// Backup processing method. Called from the worker thread. /// </summary> protected override void Backup() { if (String.IsNullOrEmpty(this.activeDriveId)) { throw new InvalidOperationException("Drive not initialized."); } // Reset the time remaining from previous burns. this.StatusUpdateArgs.TimeRemaining = TimeSpan.Zero; this.UpdateStatus(DriveStatus.Burning); MsftDiscRecorder2 discRecorder2 = new MsftDiscRecorder2(); discRecorder2.InitializeDiscRecorder(this.activeDriveId); discRecorder2.AcquireExclusiveAccess(true, ClientName); MsftDiscFormat2Data discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder2)) { throw new IOException("Invalid media."); } discFormatData.Recorder = discRecorder2; discFormatData.ClientName = ClientName; discFormatData.ForceMediaToBeClosed = true; using (var stream = this.ImageReader.ImageFile.OpenRead()) { discFormatData.Update += this.DiscFormatData_Update; try { discFormatData.Write(ComStream.ToIStream(stream)); } catch (COMException ex) { // Ignore canceled hresult. Other errors should be reported to the UI thread. if (ex.ErrorCode != -1062600702) { throw; } } finally { discFormatData.Update -= this.DiscFormatData_Update; discRecorder2.EjectMedia(); } // Double check that the burn was completed. Some cases with XP and 2003 do not // return an error, but the burn is not successful. Using progress < 99 since // the last update isn't always returned. if (!this.WorkerThread.CancellationPending && this.progress < 99) { throw new IOException("Burn not completed."); } } discRecorder2.ReleaseExclusiveAccess(); }
/// <summary> /// Get the current media type from drive letter /// </summary> /// <param name="drive"></param> /// <returns></returns> /// <remarks> /// https://stackoverflow.com/questions/11420365/detecting-if-disc-is-in-dvd-drive /// </remarks> public static MediaType?GetMediaType(Drive drive) { // Take care of the non-optical stuff first // TODO: See if any of these can be more granular, like Optical is if (drive.InternalDriveType == InternalDriveType.Floppy) { return(MediaType.FloppyDisk); } else if (drive.InternalDriveType == InternalDriveType.HardDisk) { return(MediaType.HardDisk); } else if (drive.InternalDriveType == InternalDriveType.Removable) { return(MediaType.FlashDrive); } // Get the DeviceID and MediaType from the current drive letter string deviceId = null; int mediaType = 0; try { // Get the device ID first var searcher = new ManagementObjectSearcher( "root\\CIMV2", $"SELECT * FROM Win32_CDROMDrive WHERE Id = '{drive.Letter}:\'"); foreach (ManagementObject queryObj in searcher.Get()) { deviceId = (string)queryObj["DeviceID"]; #region Possibly useful fields //foreach (var property in queryObj.Properties) //{ // Console.WriteLine(property); //} //// Capabilities list //ushort?[] capabilities = (ushort?[])queryObj["Capabilities"]; //// Internal name of the device //string caption = (string)queryObj["Caption"]; //// Flags for the file system, see FileSystemFlags //uint? fileSystemFlagsEx = (uint?)queryObj["FileSystemFlagsEx"]; //// "CD Writer" doesn't fit https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-cdromdrive //string mediaTypeString = (string)queryObj["MediaType"]; //// Internal name of the device (Seems like a duplicate of Caption) //string name = (string)queryObj["Name"]; //// Full device ID for the drive (Seems like duplicate of DeviceID) //string pnpDeviceId = (string)queryObj["PNPDeviceId"]; //// Size of the loaded media (extrapolate disc type from this?) //ulong? size = (ulong?)queryObj["Size"]; #endregion } // If we got no valid device, we don't care and just return if (deviceId == null) { return(null); } #if NET_FRAMEWORK MsftDiscMaster2 discMaster = new MsftDiscMaster2(); deviceId = deviceId.ToLower().Replace('\\', '#'); string id = null; foreach (var disc in discMaster) { if (disc.ToString().Contains(deviceId)) { id = disc.ToString(); } } // If we couldn't find the drive, we don't care and return if (id == null) { return(null); } // Otherwise, we get the media type, if any MsftDiscRecorder2 recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(id); MsftDiscFormat2Data dataWriter = new MsftDiscFormat2Data(); dataWriter.Recorder = recorder; var media = dataWriter.CurrentPhysicalMediaType; if (media != IMAPI_MEDIA_PHYSICAL_TYPE.IMAPI_MEDIA_TYPE_UNKNOWN) { return(media.IMAPIToMediaType()); } return(null); #else // TODO: This entire .NET Core path still doesn't work // This may honestly require an entire import of IMAPI2 stuff and then try // as best as possible to get it working. // Now try to get the physical media associated searcher = new ManagementObjectSearcher( "root\\CIMV2", $"SELECT * FROM Win32_PhysicalMedia"); foreach (ManagementObject queryObj in searcher.Get()) { foreach (var property in queryObj.Properties) { Console.WriteLine(property); } mediaType = (int)(queryObj["MediaType"] ?? 0); } return(((PhysicalMediaType)mediaType).ToMediaType()); #endif } catch { // We don't care what the error was return(null); } }
/// <summary> /// Selected a new device /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void devicesComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (devicesComboBox.SelectedIndex == -1) { return; } var discRecorder = (IDiscRecorder2)devicesComboBox.Items[devicesComboBox.SelectedIndex]; supportedMediaLabel.Text = string.Empty; // // Verify recorder is supported // IDiscFormat2Data discFormatData = null; try { discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsRecorderSupported(discRecorder)) { MessageBox.Show("Recorder not supported", ClientName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StringBuilder supportedMediaTypes = new StringBuilder(); foreach (IMAPI_PROFILE_TYPE profileType in discRecorder.SupportedProfiles) { string profileName = GetProfileTypeString(profileType); if (string.IsNullOrEmpty(profileName)) continue; if (supportedMediaTypes.Length > 0) supportedMediaTypes.Append(", "); supportedMediaTypes.Append(profileName); } supportedMediaLabel.Text = supportedMediaTypes.ToString(); } catch (COMException) { supportedMediaLabel.Text = "Error getting supported types"; } finally { if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
/// <summary> /// Get the current media type from drive letter /// </summary> /// <param name="driveLetter"></param> /// <returns></returns> /// <remarks> /// https://stackoverflow.com/questions/11420365/detecting-if-disc-is-in-dvd-drive /// </remarks> public static MediaType?GetMediaType(char?driveLetter) { // Get the DeviceID from the current drive letter string deviceId = null; try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_CDROMDrive WHERE Id = '" + driveLetter + ":\'"); var collection = searcher.Get(); foreach (ManagementObject queryObj in collection) { deviceId = (string)queryObj["DeviceID"]; } } catch { // We don't care what the error was return(null); } // If we got no valid device, we don't care and just return if (deviceId == null) { return(null); } // Get all relevant disc information try { MsftDiscMaster2 discMaster = new MsftDiscMaster2(); deviceId = deviceId.ToLower().Replace('\\', '#'); string id = null; foreach (var disc in discMaster) { if (disc.ToString().Contains(deviceId)) { id = disc.ToString(); } } // If we couldn't find the drive, we don't care and return if (id == null) { return(null); } // Otherwise, we get the media type, if any MsftDiscRecorder2 recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(id); MsftDiscFormat2Data dataWriter = new MsftDiscFormat2Data(); dataWriter.Recorder = recorder; var media = dataWriter.CurrentPhysicalMediaType; if (media != IMAPI_MEDIA_PHYSICAL_TYPE.IMAPI_MEDIA_TYPE_UNKNOWN) { return(Converters.ToMediaType(media)); } } catch { // We don't care what the error is } return(null); }
/// <summary> /// The thread that does the burning of the media /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscRecorder2 object // discRecorder = new MsftDiscRecorder2(); var burnData = (BurnData)e.Argument; discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId); // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data { Recorder = discRecorder, ClientName = ClientName }; // // Set the verification level // var burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = _verificationLevel; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) { multisessionInterfaces = discFormatData.MultisessionInterfaces; } // // Create the file system // IStream fileSystem; if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem)) { e.Result = -1; return; } // // add the Update event handler // discFormatData.Update += discFormatData_Update; // // Write the data here // try { discFormatData.Write(fileSystem); e.Result = 0; } catch (COMException ex) { e.Result = ex.ErrorCode; MessageBox.Show(ex.Message, "IDiscFormat2Data.Write failed", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { if (fileSystem != null) { Marshal.FinalReleaseComObject(fileSystem); } } // // remove the Update event handler // discFormatData.Update -= discFormatData_Update; if (_ejectMedia) { discRecorder.EjectMedia(); } } catch (COMException exception) { // // If anything happens during the format, show the message // MessageBox.Show(exception.Message); e.Result = exception.ErrorCode; } finally { if (discRecorder != null) { Marshal.ReleaseComObject(discRecorder); } if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
/// <summary> /// Selected a new device /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void devicesComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (devicesComboBox.SelectedIndex == -1) { return; } IDiscRecorder2 discRecorder = (IDiscRecorder2)devicesComboBox.Items[devicesComboBox.SelectedIndex]; supportedMediaLabel.Text = string.Empty; // // Verify recorder is supported // IDiscFormat2Data discFormatData = null; try { discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsRecorderSupported(discRecorder)) { MessageBox.Show("Данное устройство записи не поддерживается", m_clientName, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } StringBuilder supportedMediaTypes = new StringBuilder(); foreach (IMAPI_MEDIA_PHYSICAL_TYPE mediaType in discFormatData.SupportedMediaTypes) { if (supportedMediaTypes.Length > 0) supportedMediaTypes.Append(", "); supportedMediaTypes.Append(GetMediaTypeString(mediaType)); } supportedMediaLabel.Text = supportedMediaTypes.ToString(); } catch (COMException) { supportedMediaLabel.Text = "Ошибка получения поддерживаемых форматов"; } finally { if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
/// <summary> /// Burns a boot image and data files to disc in a single session /// using files from a single directory tree. /// </summary> /// <param name="recorder">Burning Device. Must be initialized.</param> /// <param name="path">Directory of files to burn. /// \\winbuilds\release\winmain\latest.tst\amd64fre\en-us\skus.cmi\staged\windows /// </param> /// <param name="bootFile">Path and filename of boot image. /// \\winbuilds\release\winmain\latest.tst\x86fre\bin\etfsboot.com /// </param> public void CreateBootDisc(IDiscRecorder2 recorder, String path, String bootFile) { // -------- Adding Boot Image Code ----- Console.WriteLine("Creating BootOptions"); IBootOptions bootOptions = new MsftBootOptions(); bootOptions.Manufacturer = "Microsoft"; bootOptions.PlatformId = PlatformId.PlatformX86; bootOptions.Emulation = EmulationType.EmulationNone; // Need stream for boot image file Console.WriteLine("Creating IStream for file {0}", bootFile); IStream iStream = new AStream( new FileStream(bootFile, FileMode.Open, FileAccess.Read, FileShare.Read)); bootOptions.AssignBootImage(iStream); // Create disc file system image (ISO9660 in this example) IFileSystemImage fsi = new MsftFileSystemImage(); fsi.FreeMediaBlocks = -1; // Enables larger-than-CD image fsi.FileSystemsToCreate = FsiFileSystems.FsiFileSystemISO9660 | FsiFileSystems.FsiFileSystemJoliet | FsiFileSystems.FsiFileSystemUDF; // Hooking bootStream to FileSystemObject fsi.BootImageOptions = bootOptions; // Hooking content files FileSystemObject fsi.Root.AddTree(path, false); IFileSystemImageResult result = fsi.CreateResultImage(); IStream stream= result.ImageStream; // Create and write stream to disc using the specified recorder. IDiscFormat2Data dataWriterBurn = new MsftDiscFormat2Data(); dataWriterBurn.Recorder = recorder; dataWriterBurn.ClientName = "IMAPI Sample"; dataWriterBurn.Write(stream); Console.WriteLine("----- Finished writing content -----"); }
bool if_thereIS_Disk() { if (devicesComboBox.SelectedIndex == -1) { return false; } IDiscRecorder2 discRecorder = (IDiscRecorder2)devicesComboBox.Items[devicesComboBox.SelectedIndex]; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data(); if (!discFormatData.IsCurrentMediaSupported(discRecorder)) { return false; } else { return true; } } catch { return false; } }
/// <summary> /// The thread that does the burning of the media /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void backgroundBurnWorker_DoWork(object sender, DoWorkEventArgs e) { MsftDiscRecorder2 discRecorder = null; MsftDiscFormat2Data discFormatData = null; try { // // Create and initialize the IDiscRecorder2 object // discRecorder = new MsftDiscRecorder2(); BurnData burnData = (BurnData)e.Argument; discRecorder.InitializeDiscRecorder(burnData.uniqueRecorderId); discRecorder.AcquireExclusiveAccess(true, m_clientName); // // Create and initialize the IDiscFormat2Data // discFormatData = new MsftDiscFormat2Data(); discFormatData.Recorder = discRecorder; discFormatData.ClientName = m_clientName; discFormatData.ForceMediaToBeClosed = checkBoxCloseMedia.Checked; // // Set the verification level // IBurnVerification burnVerification = (IBurnVerification)discFormatData; burnVerification.BurnVerificationLevel = (IMAPI_BURN_VERIFICATION_LEVEL)m_verificationLevel; // // Check if media is blank, (for RW media) // object[] multisessionInterfaces = null; if (!discFormatData.MediaHeuristicallyBlank) { multisessionInterfaces = discFormatData.MultisessionInterfaces; } // // Create the file system // IStream fileSystem = null; if (!CreateMediaFileSystem(discRecorder, multisessionInterfaces, out fileSystem)) { e.Result = -1; return; } // // add the Update event handler // discFormatData.Update += new DiscFormat2Data_EventHandler(discFormatData_Update); // // Write the data here // try { discFormatData.Write(fileSystem); e.Result = 0; } catch (COMException ex) { e.Result = ex.ErrorCode; MessageBox.Show(ex.Message, "Ошибка в процессе записи диска!", MessageBoxButtons.OK, MessageBoxIcon.Stop); } finally { if (fileSystem != null) { Marshal.FinalReleaseComObject(fileSystem); } } // // remove the Update event handler // discFormatData.Update -= new DiscFormat2Data_EventHandler(discFormatData_Update); if (this.checkBoxEject.Checked) { discRecorder.EjectMedia(); } discRecorder.ReleaseExclusiveAccess(); } catch (COMException exception) { // // If anything happens during the format, show the message // //MessageBox.Show(exception.Message); e.Result = exception.ErrorCode; } finally { if (discRecorder != null) { Marshal.ReleaseComObject(discRecorder); } if (discFormatData != null) { Marshal.ReleaseComObject(discFormatData); } } }
public void LoadMedia() { long mediaStateFlags; var mediaStates = new List<MediaState>(); if (!_recorderLoaded) throw new InvalidOperationException("LoadRecorder must be called first."); if (_recorders.SelectedIndex == -1) throw new InvalidOperationException("No DiscRecorder selected on the DiscRecorders list."); MsftDiscRecorder2 recorder = null; MsftFileSystemImage image = null; MsftDiscFormat2Data format = null; try { recorder = new MsftDiscRecorder2(); recorder.InitializeDiscRecorder(_recorders.SelectedItem.InternalUniqueId); format = new MsftDiscFormat2Data(); if (!format.IsCurrentMediaSupported(recorder)) throw new MediaNotSupportedException("There is no media in the device."); // // Get the media type in the recorder // format.Recorder = recorder; _media = (PhysicalMedia)format.CurrentPhysicalMediaType; mediaStateFlags = (long)format.CurrentMediaStatus; foreach (MediaState state in Enum.GetValues(typeof(MediaState))) { if (((long)mediaStateFlags & (long)state) > 0) mediaStates.Add(state); } if (mediaStates.Count == 0) mediaStates.Add(MediaState.Unknown); _mediaStates = new ReadOnlyCollection<MediaState>(mediaStates); if ((mediaStateFlags & (long)IMAPI_FORMAT2_DATA_MEDIA_STATE.IMAPI_FORMAT2_DATA_MEDIA_STATE_WRITE_PROTECTED) > 0) throw new MediaNotSupportedException("The media in the device is write protected."); // // Create a file system and select the media type // image = new MsftFileSystemImage(); image.ChooseImageDefaultsForMediaType((IMAPI_MEDIA_PHYSICAL_TYPE)_media); // // See if there are other recorded sessions on the disc // if (!format.MediaHeuristicallyBlank) { image.MultisessionInterfaces = format.MultisessionInterfaces; image.ImportFileSystem(); } _mediaCapacity = 2048 * image.FreeMediaBlocks; _mediaLoaded = true; } finally { if (image != null) Marshal.ReleaseComObject(image); if (format != null) Marshal.ReleaseComObject(format); if (recorder != null) Marshal.ReleaseComObject(recorder); } }