What's the best way to get the default printer in .NET
Solution 1:
The easiest way I found is to create a new PrinterSettings
object. It starts with all default values, so you can check its Name property to get the name of the default printer.
PrinterSettings
is in System.Drawing.dll in the namespace System.Drawing.Printing
.
PrinterSettings settings = new PrinterSettings();
Console.WriteLine(settings.PrinterName);
Alternatively, you could maybe use the static PrinterSettings.InstalledPrinters
method to get a list of all printer names, then set the PrinterName property and check the IsDefaultPrinter. I haven't tried this, but the documentation seems to suggest it won't work. Apparently IsDefaultPrinter is only true when PrinterName is not explicitly set.
Solution 2:
Another approach is using WMI (you'll need to add a reference to the System.Management assembly):
public static string GetDefaultPrinterName()
{
var query = new ObjectQuery("SELECT * FROM Win32_Printer");
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
if (((bool?) mo["Default"]) ?? false)
{
return mo["Name"] as string;
}
}
return null;
}
Solution 3:
If you just want the printer name no advantage at all. But WMI is capable of returning a whole bunch of other printer properties:
using System;
using System.Management;
namespace Test
{
class Program
{
static void Main(string[] args)
{
ObjectQuery query = new ObjectQuery(
"Select * From Win32_Printer " +
"Where Default = True");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(query);
foreach (ManagementObject mo in searcher.Get())
{
Console.WriteLine(mo["Name"] + "\n");
foreach (PropertyData p in mo.Properties)
{
Console.WriteLine(p.Name );
}
}
}
}
}
and not just printers. If you are interested in any kind of computer related data, chances are you can get it with WMI. WQL (the WMI version of SQL) is also one of its advantages.