예제 #1
0
        public static bool RemoveFromSystem(
            SetupApi.DeviceInfoSet devInfoSet,
            string hwID,
            bool strictSearch)
        // WARNING: Removes ONLY the particular device
        // instance referenced by 'devInfoSet'
        {
            SetupApi.SP_DEVINFO_DATA devInfoData;

            devInfoData = FindInSystem(
                hwID,
                devInfoSet,
                strictSearch
                );

            if (devInfoData == null)
            {
                return(false);
            }

            SetupApi.SP_REMOVEDEVICE_PARAMS rparams =
                new SetupApi.SP_REMOVEDEVICE_PARAMS();

            rparams.ClassInstallHeader.cbSize =
                (uint)Marshal.SizeOf(rparams.ClassInstallHeader);

            rparams.ClassInstallHeader.InstallFunction =
                SetupApi.DI_FUNCTION.DIF_REMOVE;

            rparams.HwProfile = 0;
            rparams.Scope     = SetupApi.DI_REMOVE_DEVICE_GLOBAL;
            GCHandle handle1 = GCHandle.Alloc(rparams);

            if (!SetupApi.SetupDiSetClassInstallParams(
                    devInfoSet.Get(),
                    devInfoData,
                    ref rparams,
                    Marshal.SizeOf(rparams)))
            {
                Win32Error.Set("SetupDiSetClassInstallParams");
                throw new Exception(
                          Win32Error.GetFullErrMsg()
                          );
            }

            Trace.WriteLine(
                "Removing device \'" + hwID +
                "\' from system"
                );

            if (!SetupApi.SetupDiCallClassInstaller(
                    SetupApi.DI_FUNCTION.DIF_REMOVE,
                    devInfoSet.Get(),
                    devInfoData))
            {
                Win32Error.Set("SetupDiCallClassInstaller");
                if (Win32Error.GetErrorNo() != WinError.ERROR_KEY_DOES_NOT_EXIST)
                {
                    throw new Exception(
                              Win32Error.GetFullErrMsg()
                              );
                }
            }

            Trace.WriteLine("Remove should have worked");
            return(true);
        }
예제 #2
0
        public static string GetUserSidFromSessionId(UInt32 sessionId)
        // Gets the unique Security Identifier (SID)
        // of the User logged on to 'sessionId'
        {
            IntPtr token       = (IntPtr)0;
            IntPtr tokenInf    = IntPtr.Zero;
            uint   tokenInfLen = 0;
            IntPtr szSid       = IntPtr.Zero;
            string sid;

            try
            {
                AcquireSystemPrivilege(AdvApi32.SE_TCB_NAME);

                Trace.WriteLine("Using session id " + sessionId.ToString());
                if (!WtsApi32.WTSQueryUserToken(sessionId, out token))
                {
                    Win32Error.Set("WTSQueryUserToken");
                    throw new Exception(Win32Error.GetFullErrMsg());
                }

                // Get tokenInfLen
                AdvApi32.GetTokenInformation(
                    token,
                    AdvApi32.TOKEN_INFORMATION_CLASS.TokenUser,
                    tokenInf,
                    tokenInfLen,
                    out tokenInfLen
                    );

                Win32Error.Set("GetTokenInformation");

                if (Win32Error.GetErrorNo() !=
                    WinError.ERROR_INSUFFICIENT_BUFFER)
                {
                    throw new Exception(Win32Error.GetFullErrMsg());
                }

                tokenInf = Marshal.AllocHGlobal((int)tokenInfLen);

                if (!AdvApi32.GetTokenInformation(
                        token,
                        AdvApi32.TOKEN_INFORMATION_CLASS.TokenUser,
                        tokenInf,
                        tokenInfLen,
                        out tokenInfLen))
                {
                    Win32Error.Set("GetTokenInformation");
                    throw new Exception(Win32Error.GetFullErrMsg());
                }

                AdvApi32.TOKEN_USER tokenUser =
                    (AdvApi32.TOKEN_USER)Marshal.PtrToStructure(
                        tokenInf,
                        typeof(AdvApi32.TOKEN_USER)
                        );

                if (!AdvApi32.ConvertSidToStringSid(
                        tokenUser.User.Sid,
                        out szSid))
                {
                    Win32Error.Set("ConvertSidToStringSid");
                    throw new Exception(Win32Error.GetFullErrMsg());
                }

                sid = Marshal.PtrToStringAuto(szSid);

                return(sid);
            }
            finally
            {
                if (szSid != IntPtr.Zero)
                {
                    Kernel32.LocalFree(szSid);
                }
                if (tokenInf != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(tokenInf);
                }
                if (token != IntPtr.Zero)
                {
                    Kernel32.CloseHandle(token);
                }
            }
        }
예제 #3
0
        public static SetupApi.SP_DEVINFO_DATA FindInSystem(
            string hwID,
            SetupApi.DeviceInfoSet devInfoSet,
            bool strictSearch)
        // The function takes as input an initialized 'deviceInfoSet'
        // object and a hardware ID string we want to search the system
        // for. If 'strictSearch' is true, the device needs to exactly
        // match the hwID to be returned. Otherwise, the device's name
        // needs to start with the supplied hwID string. If the device
        // is found, a fully initialized 'SP_DEVINFO_DATA' object is
        // returned. If not, the function returns 'null'.
        {
            SetupApi.SP_DEVINFO_DATA devInfoData =
                new SetupApi.SP_DEVINFO_DATA();
            devInfoData.cbSize = (uint)Marshal.SizeOf(devInfoData);

            // Select which string comparison function
            // to use, depending on 'strictSearch'
            Func <string, string, bool> hwIDFound;

            if (strictSearch)
            {
                hwIDFound = (string _enumID, string _hwID) =>
                            _enumID.Equals(
                    _hwID,
                    StringComparison.OrdinalIgnoreCase
                    );
            }
            else
            {
                hwIDFound = (string _enumID, string _hwID) =>
                            _enumID.StartsWith(
                    _hwID,
                    StringComparison.OrdinalIgnoreCase
                    );
            }

            Trace.WriteLine(
                "Searching system for device: \'" + hwID +
                "\'; (strict search: \'" + strictSearch + "\')"
                );

            for (uint i = 0;
                 SetupApi.SetupDiEnumDeviceInfo(
                     devInfoSet.Get(),
                     i,
                     devInfoData);
                 ++i)
            {
                string [] ids = GetDevRegPropertyMultiStr(
                    devInfoSet,
                    devInfoData,
                    SetupApi.SPDRP.HARDWAREID
                    );

                foreach (string id in ids)
                {
                    if (hwIDFound(id, hwID))
                    {
                        Trace.WriteLine(
                            "Found: \'" + String.Join("  ", ids) + "\'"
                            );
                        return(devInfoData);
                    }
                }
            }

            Win32Error.Set("SetupDiEnumDeviceInfo");
            if (Win32Error.GetErrorNo() == WinError.ERROR_NO_MORE_ITEMS)
            {
                Trace.WriteLine("Device not found");
                return(null);
            }

            throw new Exception(Win32Error.GetFullErrMsg());
        }
예제 #4
0
        public static void InstallDriver(
            string name,
            string infPath,
            out bool reboot,
            NewDev.DIIRFLAG flags = NewDev.DIIRFLAG.ZERO)
        {
            Trace.WriteLine("Add to driverstore " + infPath);
            int size = 0;

            bool success   = SetupApi.SetupCopyOEMInf(infPath, "", SetupApi.SPOST.NONE, SetupApi.SP_COPY.NOOVERWRITE, IntPtr.Zero, 0, ref size, IntPtr.Zero);
            bool bcontinue = true;

            reboot = false;
            if (!success)
            {
                int error = Marshal.GetLastWin32Error();
                Trace.WriteLine("Unable to update driver - code " + error.ToString());
                if ((error == 0) || (error == 0x50))
                {
                    // We still try to install the driver even the OEMInf file has already been copied,
                    // For the case of install driver not finished, but system shutdown
                    Trace.WriteLine("OEMInf file already copied");
                }
                else
                {
                    bcontinue = false; // Other error, does not continue
                }
            }

            if (!bcontinue)
            {
                return;
            }
            Trace.WriteLine(
                "Installing driver: \'" + Path.GetFileName(infPath) + "\'"
                );



            NewDev.DiInstallDriver(
                IntPtr.Zero,
                infPath,
                flags,
                out reboot
                );

            Win32Error.Set("DiInstallDriver");

            if (Win32Error.GetErrorNo() == WinError.ERROR_SUCCESS)
            {
                Trace.WriteLine("Driver installed successfully");
            }
            else if (Win32Error.GetErrorNo() == WinError.ERROR_NO_MORE_ITEMS)
            // DiInstallDriver() returns ERROR_NO_MORE_ITEMS when the
            // hardware ID in the inf file is found, but the specified
            // driver is not a better match than the current one and
            // DIIRFLAG_FORCE_INF is not used
            {
                Trace.WriteLine(
                    "Driver not installed; newer driver already present"
                    );
            }
            else
            {
                throw new Exception(Win32Error.GetFullErrMsg());
            }
        }