NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

Here's a static method that sets a printer as the default on a system, using the windows scripting host network stuff from C#.  It's here so I can look it up if anyone else asks in future since I couldn't easily find how to do this in C#...  (I know the exception handling is poor)

/// <summary>
/// Sets a default printer
/// </summary>
/// <param name="name"></param>
public static void SetDefaultPrinter(string name)
{
   try
   {
      //late bind to the wsh network com object
      //create an instance of a reflection type
      Type t = Type.GetTypeFromProgID("WScript.Network");
      //create an instance using the system activator, consuming the type
      Object o = Activator.CreateInstance(t);
      //invoke the method using the object we created
      t.InvokeMember("SetDefaultPrinter", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] {name});
   } 
   catch (Exception)
   {
      throw new Exception("Unable to set a default printer. The printer may not exist or the WScript.Network com object may have a problem.");
   }
}

Permalink