在UWP应用中获取默认打印机驱动的IP地址
Got it, let's work through this problem where you can grab the printer port name but not the actual IP address in your UWP app. The key issue here is that System.Devices.IpAddress isn't directly exposed on the printer device interface itself—it lives on the associated network port device instead. Here's how to get it reliably:
Step 1: Get the Default Printer's Port Name
First, use the PrinterQueue class to fetch the default printer and its port name. This is more straightforward than digging through DeviceInformation directly for printer-specific details:
using Windows.Devices.Printers; using Windows.Devices.Enumeration; async Task<string> GetDefaultPrinterIpAsync() { // Fetch the default printer queue var defaultQueue = await PrinterQueue.GetDefaultAsync(); if (defaultQueue == null) { return null; // No default printer set } string portName = defaultQueue.PortName;
Step 2: Find the Associated Network Port Device
Printer ports have their own device interface class GUID: {0ecef634-6ef0-472a-8085-5ad023ecbccd}. We'll use this to search for the port device matching our printer's port name, and request the System.Devices.IpAddress property explicitly:
// Define the printer port interface class GUID string portInterfaceClass = "System.DeviceInterfaceClass.{0ecef634-6ef0-472a-8085-5ad023ecbccd}"; // Search for the port device matching our printer's port name var portDevices = await DeviceInformation.FindAllAsync( portInterfaceClass, new[] { "System.Devices.IpAddress", "System.DeviceInterface.PrinterPortName" }, $"System.DeviceInterface.PrinterPortName:=\"{portName}\"" ); if (portDevices.Count == 0) { return null; // No matching port found (e.g., USB printer) }
Step 3: Extract the IP Address
Once we have the port device, we can pull the IP address from its properties:
var portDevice = portDevices[0]; if (portDevice.Properties.TryGetValue("System.Devices.IpAddress", out object ipObj)) { return ipObj.ToString(); } return null; }
Critical Notes
- Permissions: Make sure your UWP app declares the necessary capabilities in
Package.appxmanifest:<Capabilities> <DeviceCapability Name="print" /> <Capability Name="internetClient" /> <Capability Name="privateNetworkClientServer" /> </Capabilities> - Non-network Printers: USB or local printers won't have an IP address—add checks to handle these cases gracefully.
- Why Your Initial Attempt Failed:
System.Devices.IpAddressis a property of the network port device, not the printer's main device interface. You have to traverse to the associated port to access it.
内容的提问来源于stack exchange,提问作者SiD

