Eject SSD drive from C# code

sathish viswanathan 1 Reputation point
2021-06-30T18:24:13.247+00:00

I have been trying to remove an SSD drive from C# code. I can eject USB drive but doesn't with SSD drive
Found a WinAPI call CM_Request_Device_Eject, however I am having trouble getting it to work.

Please find the code snippet

Unicode implemetation :

        [DllImport("setupapi.dll")]
        static extern int CM_Request_Device_Eject(
            int dnDevInst,
            out PNP_VETO_TYPE pVetoType,
            StringBuilder pszVetoName,
            int ulNameLength,
            int ulFlags);

        [DllImport("setupapi.dll", EntryPoint = "CM_Request_Device_Eject")]
        static extern int CM_Request_Device_Eject_NoUi(
            int dnDevInst,
            IntPtr pVetoType,
            StringBuilder pszVetoName,
            int ulNameLength,
            int ulFlags);

Method call :

int r = CM_Request_Device_Eject_NoUi(DevInstParent, IntPtr.Zero, null, 0, 0);

If anyone can help me with a code snippet or guide me in the right direction it would be very appreciated.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,237 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Castorix31 81,636 Reputation points
    2021-06-30T19:05:02.62+00:00

    It is the same question as Eject SSD from c++ code
    The OP said that the method with CM_Request_Device_Eject did not work, but the one I posted with HotPlugEjectDevice worked
    (P/Invoke in C#)

    2 people found this answer helpful.
    0 comments No comments

  2. sathish viswanathan 1 Reputation point
    2021-07-04T17:11:02.997+00:00

    Thanks for the reply. I tried above mentioned link, I’m able to run successfully in C++ but doesn't with C#. can you please suggest what I missing here.

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate object HPED(IntPtr hWnd, string DeviceInstanceId, uint dwFlags);

        static void Main(string[] args)
        {
    
         IntPtr hDLL = LoadLibrary(@"c:\\Windows\\System32\\HotPlug.dll");
         HPED HotPlugEjectDevice = null;
    
            if (hDLL != null)
            {
                IntPtr s =GetProcAddress(hDLL, "HotPlugEjectDevice");
                if (HotPlugEjectDevice != null)
                {
                    object obj= HotPlugEjectDevice(IntPtr.Zero, @"SCSI\\DISK&VEN_&PROD_MTFDDAK256TDL\\4&3118ADCB&0&010000", 0);
    
                }
            }
    
            bool result = FreeLibrary(hDLL);       
    
            Console.WriteLine(result);
        }