Click here to Skip to main content
16,017,954 members
Articles / Programming Languages / C#
Article

Set Default Printer based on the Network that the System Connected

Rate me:
Please Sign up or sign in to vote.
2.86/5 (6 votes)
27 May 2008CPOL1 min read 73.3K   921   22   4
Set Default Printer based on the Network that the System Connected

Introduction

This is a small utility to set the default printer of the local system based on the network that the system is connected to.

This utility gets the printer-network mapping from an XML file. This enables the user to modify the printer-network mapping.

This utility uses Windows Management Instruments (WMI) to access system printers information and set the default printer based on the user selection.

To know more about Windows Management Instruments, check this link.

System.Management namespace provides a powerful class to access various types of system information.

Limitation of WMI

WMI does not work properly with Windows 2000. It works fine with Windows XP Service Pack 2 or Windows Vista. For more information, check this Web site.

There is another problem that I faced while developing this utility.
Debugging the code. Enumerating through a ManagementObjectCollection is not possible. 

In addition, the properties of a ManagementObject are unknown. I had to get through the Internet to find proper documentation. But I didn't find one.

How It Works

To get a particular device or system information, ManagementObjectSearcher or ManagementQuery is used.

C#
///Query using WMI to fetch the NIC information from windows.
string query = String.Format("SELECT * FROM Win32_NetworkAdapterConfiguration"
	+ " WHERE MACAddress = '{0}'", macAddress.ToString());

ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();
///Throw Exception if Not found
if (moCollection.Count == 0)
	throw new Exception(String.Format("The NIC Card ({0}) 
		information not found in windows.", macAddress.ToString()));

List<networkadapterconfiguration /> config = new List<networkadapterconfiguration />();
///Extract the Data and assign in config
foreach (ManagementObject mo in moCollection)
{
	// IPAddresses, probably have more than one value
	string[] addresses = (string[])mo["IPAddress"];
	if (addresses == null) continue;

	if (addresses[0] != ni.GetIPProperties().UnicastAddresses[0].Address.ToString())
		continue;
	//config.MachineAddress = addresses[0];
	// IPSubnets, probably have more than one value
	string[] subnets = (string[])mo["IPSubnet"];
	//config.SubnetMask = subnets[0];
	//config.NetworkAddress = CalculateNetworkAddress(
	//    config.MachineAddress, config.SubnetMask);
}

You can also access system resource information if you know the full path of the resource as follows:

C#
String printerPath="win32_printer.DeviceId='" + printerName + "'";

ManagementObject printer = new ManagementObject(printerPath);

Using ManagementObjectSearcher:

C#
ManagementScope scope = new ManagementScope(@"\root\cimv2");
pscope.Connect();

// Select Printers from WMI Object Collections
ManagementObjectSearcher searcher = new
ManagementObjectSearcher(QUERY_ALLPRINTER);

return searcher.Get();

Setting the Default Printer

To set the default printer:

C#
ManagementBaseObject outParams;
try
{
	outParams = printer.InvokeMethod("SetDefaultPrinter", null, null);
	if (outParams == null)
		throw new Exception("Unable to set default printer.");
	Int32 retVal = (int)(uint)outParams.Properties["ReturnValue"].Value;
	if (retVal == 0)
		return true;
	else
		return false;
}
catch (Exception ex)
{
	throw ex;
}

Network Address Calculation

To get the Network Address (Network ID) of the system, the following code is used:

C#
public static String CalculateNetworkAddress(String ip, String mask)
{
	IPAddress _ip;
	IPAddress _subnet;

	if (!IPAddress.TryParse(ip, out _ip))
		throw new FormatException
		(PrinterUtility.Properties.Resources.IPAddressException);

	if (!IPAddress.TryParse(mask, out _subnet))
		throw new FormatException
		(PrinterUtility.Properties.Resources.SubnetMaskException);
            
	StringBuilder networkAddress = new StringBuilder("");
            
	for (int index = 0; index < 4; index++)
	{
		int networkAddressBlock = _ip.GetAddressBytes()[index] & 
					_subnet.GetAddressBytes()[index];
		networkAddress.Append(networkAddressBlock.ToString());
		networkAddress.Append(".");
	}
	return networkAddress.ToString().TrimEnd('.'); ;
}

Before that, you have to get the system IP Address and Subnet Mask. To do that, you can use NetworkInterface class under System.Net:

C#
NetworkInterface[] nis =NetworkInterface.GetAllNetworkInterfaces();

History

  • 27th May, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer SDL Tridion
Netherlands Netherlands
Software Developer with extensive experience in Software Development. Six years of Job experience in different positions. Eight years of practical experience in .net development. Experience in Distributed Application Development, Service Oriented Application Development and Smart Client Application development using .net framework.

More About Me:
http://iambappi.wordpress.com
http://iambappi.spaces.live.com/

Comments and Discussions

 
GeneralAwesome article Pin
Razan Paul (Raju)12-Jun-08 21:08
Razan Paul (Raju)12-Jun-08 21:08 
GeneralMgmtClassGen.exe Pin
pefl12-Jun-08 3:07
pefl12-Jun-08 3:07 
Is there any reason you don't use the WMI wrappers created by MgmtClassGen.exe ?
The only code you need to set the default printer is the following then:
Printer p = new Printer(myPrinterName);
p.SetDefaultPrinter();

GeneralRe: MgmtClassGen.exe Pin
Bappi M Ahmed17-Jun-08 22:52
Bappi M Ahmed17-Jun-08 22:52 
GeneralNice Article Pin
setu_raas9-Jun-08 0:02
setu_raas9-Jun-08 0:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.