Retrieve IP Address of the Default Printer Driver

2020-08-01 06:45发布

问题:

We have a requirement to get the printer IP Address configured in the default printer driver in Control Panel in our UWP app.

I was able to retrieve the "System.DeviceInterface.PrinterPortName" by fetching interface class GUID and passing this above property for retrieval.

But I couldn't get "System.Devices.IpAddress" similarly. Code pasted below for PortName.

I badly need the IP address as the port name is user's choice and could be modified to any name removing the IP address.

Kindly help sharing working code to retrieve the IP Address using above property or any other way in UWP app.

Below is Working Code for Port Name, Kindly help to fetch IP Address of the same port similarly.

        string aqsFilter = "System.Devices.InterfaceClassGuid:=\"{0ecef634-6ef0-472a-8085-5ad023ecbccd}\"";

        string[] propertiesToRetrieve = new string[] { "System.DeviceInterface.PrinterPortName"};

        DeviceInformationCollection deviceInfoCollection = await DeviceInformation.FindAllAsync(aqsFilter, propertiesToRetrieve);

        foreach (DeviceInformation deviceInfo in deviceInfoCollection)
        {
            if (deviceInfo.IsDefault == true)
            {
                string strPortName = (string)deviceInfo.Properties["System.DeviceInterface.PrinterPortName"];

                if (!string.IsNullOrEmpty(strPortName))
                {
                    strPortName = await ParsePortName(strPortName);
                    if (!string.IsNullOrEmpty(strPortName))
                    {
                        _strIPAddress = strPortName;
                    }
                }
                break;
            }
        }

回答1:

This is not endorsed because the IP address can change and so it is unreliable.

That being said, if your printer is installed using wsd, it is technically supported E.g., DEVPKEY_PNPX_IpAddress DEVPROP_TYPE_STRING_LIST 32 "10.137.192.202" But there is no way to reliably use this without a lot of various scenario checks since the IP address may change.

Furthermore, looking at this example, you are not hitting the DAF providers but looking for devices. You are using 0ecef634-6ef0-472a-8085-5ad023ecbccd which is the printer class guid. It also does not look like IP address is propagated in the PnP Explorer property bag so the IP address is not accessible.