Click here to Skip to main content
13,257,666 members (76,605 online)
Click here to Skip to main content
Add your own
alternative version


6 bookmarked
Posted 28 Oct 2010

Magnetic Tape Data Storage. Part 2: Media Changer - Status Commands

, 28 Oct 2010
Rate this:
Please Sign up or sign in to vote.
Media changer status commands implementations in C#


This article describes the procedures and issues involved in the development of software applications to communicate with the Media Changer and to obtain basic information about its internal structure.

Discovering Changer Name

The first operation that should be done is to create OS handle to Media changer. Handle can be obtained by CreateFile API.

[DllImport("kernel32.dll", CharSet = CharSet.Auto, 
	CallingConvention = CallingConvention.StdCall, SetLastError = true)]
    public static extern SafeFileHandle CreateFile(
          uint dwDesiredAccess,
          uint dwShareMode,
          IntPtr SecurityAttributes,
          uint dwCreationDisposition,
          uint dwFlagsAndAttributes,
          IntPtr hTemplateFile

As you can see, the first parameter is file name. Most attached hardware devices get unique system names, a.k.a. DOS name. Media changer can get the following system names: MediaChangeX, ChangerX. To obtain the exact name, we can call the Win API method:

   static extern uint QueryDosDevice(string lpDeviceName,
   IntPtr lpTargetPath, uint ucchMax);

   private static string QueryDosDevice()
       IntPtr mem = Marshal.AllocHGlobal(1024);

           if (mem == IntPtr.Zero)
               throw new Win32Exception("Failed to allocate unmanaged memory");

           uint returnSize = (int)QueryDosDevice(null, mem, (uint)maxSize);
           if (returnSize == 0)
               throw new Win32Exception("Failed to obtain DOS devices info");

           string allDevices = Marshal.PtrToStringAnsi(mem, returnSize);
           return allDevices;
           if(mem != IntPtr.Zero )
   // Output(Fragment)
   // ...
   // ...

The returned string will contain all system DOS names. Search for Changer or MediaChanger words. You will find the exact name for your Media Changer. If you have two or more Media Changers attached to your machine, you can use DeviceIOControl to obtain address information, such as the target ID (TID) and the logical unit number (LUN) of a particular SCSI target. So you will get the information whose DOS name is allocated for device that you are working with.

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool DeviceIoControl(
        SafeFileHandle hDevice,
        uint dwIoControlCode,
        IntPtr lpInBuffer,
        uint nInBufferSize,
        IntPtr lpOutBuffer,
        uint nOutBufferSize,
        out uint lpBytesReturned,
        IntPtr lpOverlapped);

    private static string MapDosName(string fileHandle)
        IntPtr ptr = Marshal.AllocHGlobal(1024);
            bool status = SCSI.DeviceIoControl(
                    out returned,

            if (status == false)
                return string.Format("Error opening the DEVICE {0}", 

            return string.Format("Length={0}, PortNumber={1}, PathId={2}, 
			TargetId={3}, Lun={4}",
                Marshal.ReadInt32(ptr, 0),
                Marshal.ReadByte(ptr, 4),
                Marshal.ReadByte(ptr, 5),
                Marshal.ReadByte(ptr, 6),
                Marshal.ReadByte(ptr, 7));
    // Output (fileHandle is created from \\.\Changer0):
    // Changer0
    // Length:8, TargetID:2, LUN:1, PathID:0, Port:3

Discovering Changer Structure

Now, we have enough information to work with Media Changer Device, so we will focus on the API function that causes a SCSI BUS Changer device to return information about itself. For example, some devices can have the following internal structure (logical):


As you remember, magnetic tape data storage is an integration of two separate devices, a tape drive and a media changer. The media changer consists of all the mechanics and electronics required to store and move tape cartridges while the tape drive provides the read/write functionality. So when tape is inserted to the devices it goes to the Mail Slot. From mail slot, it can be moved to regular slot (slots 1-8) or Drive. When the tape is in Drive, it is possible to perform IO operations. Let’s see how discovering can be done by C# code. One of the possible ways is performing IOCTL_CHANGER_GET_ELEMENT_STATUS call. See Discover method, this method will type status for each existing regular slot and for the drive.

public Changer.ChangerElementStatusEx
            GetElementStatus(uint address, Changer.ElementType elementType)
        IntPtr ptrIn = IntPtr.Zero;
        IntPtr ptrOut = IntPtr.Zero;
            m_Log.Debug("ENTER GetElementStatus");
            Changer.ChangerReadElementStatus readStatusIn = 
			new Changer.ChangerReadElementStatus();

            readStatusIn.ElementList.NumberOfElements = 1;
            readStatusIn.ElementList.Element.ElementAddress = address;
            readStatusIn.ElementList.Element.ElementType = elementType;
            readStatusIn.VolumeTagInfo = 1;

            ptrIn = Marshal.AllocHGlobal(Marshal.SizeOf(readStatusIn));
            Marshal.StructureToPtr(readStatusIn, ptrIn, true);

            Changer.ChangerElementStatusEx driveStatus = 
			new Changer.ChangerElementStatusEx();
            ptrOut = Marshal.AllocHGlobal(Marshal.SizeOf(driveStatus));

            uint readBytes;
            if (false == Changer.DeviceIoControl(
                ChangerHandle,                                      // handle to device
                (uint)Changer.IOCTL_CHANGER_GET_ELEMENT_STATUS,     // dwIoControlCode
                ptrIn,                                              // lpInBuffer
                (uint)Marshal.SizeOf(readStatusIn),                 // nInBufferSize
                ptrOut,                                             // output buffer
                (uint)Marshal.SizeOf(driveStatus),         // size of output buffer
                out readBytes,                             // number of bytes returned
                IntPtr.Zero                                // OVERLAPPED structure
                int error = Marshal.GetLastWin32Error();
                throw new Win32Exception(error, "Cannot access device, error:" + error);

            driveStatus = (Changer.ChangerElementStatusEx)Marshal.PtrToStructure
			(ptrOut, driveStatus.GetType());

            return driveStatus;
        catch (Exception e)
            m_Log.Error("GetElementStatus", e);
            if (ptrIn != IntPtr.Zero)
            if (ptrOut != IntPtr.Zero)
            m_Log.Debug("EXIT GetElementStatus");

    public void Discover()
        int errorCode = 0;

        Changer.ChangerElementStatusEx status;

        for(int i = 0; i++; i < int.MaxValue)
                status = GetElementStatus((uint)i, Changer.ElementType.ChangerSlot);
                m_Log.InfoFormat("Regular slot {0} is {1} empty", 
				i, status.IsEmpty ? "" : "not");
            catch (Win32Exception e)
                if (e.NativeErrorCode == 
		ERROR_ILLEGAL_ELEMENT_ADDRESS) break; //no more elements


        status = m_TapeOperator.GetElementStatus(0, Changer.ElementType.ChangerDrive);
        m_Log.InfoFormat("Driver is {0} empty", status.IsEmpty ? "" : "not");


This article covered Status functionality of Media Changers. When status of Media Changer is obtained, we can perform MOVE, EJECT, INSERT and IO functionality to perform pretty good backup system.

For IO functionality, you can see Magnetic tape data storage. Part 1.

MOVE, EJECT and INSERT will be covered in the next article.


  • 28th October, 2010: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Dima Statz
Israel Israel
Name: Statz Dima
Fields of interest: software

You may also be interested in...

Comments and Discussions

QuestionTape Library inventorying Pin
Murali Mano12-Feb-17 23:53
memberMurali Mano12-Feb-17 23:53 
QuestionGreat Article Pin
Member 39272021-Aug-13 10:08
memberMember 39272021-Aug-13 10:08 
QuestionError 5 Pin
seyed ali ehbali26-May-12 4:49
memberseyed ali ehbali26-May-12 4:49 
Questionwaiting for the third part Pin
amini_porroo30-Apr-12 21:56
memberamini_porroo30-Apr-12 21:56 
QuestionTape IO with media changer Pin
billl papan12-Mar-12 5:36
memberbilll papan12-Mar-12 5:36 
Questionno Changer driver therfore no changer "device", what then? Pin
Member 263752619-Oct-11 13:53
memberMember 263752619-Oct-11 13:53 
AnswerRe: no Changer driver therfore no changer "device", what then? Pin
Dima Statsenko20-Oct-11 8:34
memberDima Statsenko20-Oct-11 8:34 
QuestionCode? Pin
fssd16-Feb-11 11:43
memberfssd16-Feb-11 11:43 
AnswerRe: Code? [modified] Pin
Dima Statsenko22-Feb-11 23:09
memberDima Statsenko22-Feb-11 23:09 
GeneralRe: Code? [modified] Pin
seyed ali ehbali16-Jun-12 23:31
memberseyed ali ehbali16-Jun-12 23:31 
GeneralRe: Code? [modified] Pin
BillyDvd29-Jun-12 7:21
memberBillyDvd29-Jun-12 7:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 28 Oct 2010
Article Copyright 2010 by Dima Statz
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid