1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             const string printerName = "Print to file";
 6             const string portName = "FILE:";
 7             const string driverName = "ZEBRA R110Xi4 300DPI";
 8 
 9             PrinterPorts printerPorts = new PrinterPorts();
10 
11             var portNames = printerPorts.GetPortNames();
12             //判断端口是否存在
13             if (!portNames.Contains(portName))
14             {
15                 Console.WriteLine("{0} port is not existed", portName);
16                 return;
17             }
18 
19             var driverNames = GetDrivers();
20             //判断Driver是否存在
21             if (!driverNames.Contains(driverName))
22             {
23                 Console.WriteLine("{0} driver is not existed", driverName);
24                 return;
25             }
26 
27             AddPrinter(printerName, portName, driverName);
28 
29             Console.ReadKey();
30         }
31 
32         private static void AddPrinter(string printerName, string portName,string printerDriver)
33         {
34             try
35             {
36                 //init Win32_Printer class     
37                 var printerClass = new ManagementClass("Win32_Printer");
38 
39                 //create new Win32_Printer object   
40                 ManagementObject printerObject = printerClass.CreateInstance();
41 
42                 if (printerObject == null)
43                 {
44                     throw new Exception("printerObject is null");
45                 }
46 
47                 printerObject["PortName"] = portName;
48                 //set driver and device names              
49                 printerObject["DriverName"] = printerDriver;
50 
51                 printerObject["DeviceID"] = printerName;
52 
53                 // specify put options: update or create              
54                 PutOptions options = new PutOptions();
55                 options.Type = PutType.UpdateOrCreate;
56                 //put a newly created object to WMI objects set              
57                 printerObject.Put(options);
58             }
59             catch (Exception ex)
60             {
61                 throw new Exception(String.Format("WMI exception: {0}", ex.Message));
62             }
63         }
64 
65         /// <summary>
66         /// Get's a list of drives installed on the computer
67         /// </summary>
68         /// <returns></returns>
69         private static List<string> GetDrivers()
70         {
71             var drivers = new List<string>();
72 
73             var selectQuery = new SelectQuery("Win32_PrinterDriver");
74             var searcher = new ManagementObjectSearcher(selectQuery);
75 
76             foreach (ManagementObject printerDriver in searcher.Get())
77             {
78                 // Your code here.
79                 var obj = printerDriver["name"];
80                 string name = string.Empty;
81 
82                 if (obj != null)
83                 {
84                     name = obj.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0];
85                 }
86 
87                 drivers.Add(name);
88             }
89 
90             return drivers;
91         }
92 
93     }
 1     class PrinterPorts
 2     {
 3         //PortType enum
 4         [Flags]
 5         public enum PortType : int
 6         {
 7             write = 0x1,
 8             read = 0x2,
 9             redirected = 0x4,
10             net_attached = 0x8
11         }
12 
13 
14         //struct for PORT_INFO_2
15         [StructLayout(LayoutKind.Sequential)]
16         public struct PORT_INFO_2
17         {
18             public string pPortName;
19             public string pMonitorName;
20             public string pDescription;
21             public PortType fPortType;
22             internal int Reserved;
23         }
24 
25         //Win32 API
26         [DllImport("winspool.drv", EntryPoint = "EnumPortsA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
27         public static extern int EnumPorts(string pName, int Level, IntPtr lpbPorts, int cbBuf, ref int pcbNeeded, ref int pcReturned);
28 
29 
30         /// <summary>
31         /// method for retrieving all available printer ports
32         /// </summary>
33         /// <returns>generic list populated with post names (i.e; COM1, LTP1, etc)</returns>
34         public List<string> GetPortNames()
35         {
36             //variables needed for Win32 API calls
37             int result; int needed = 0; int cnt = 0; IntPtr buffer = IntPtr.Zero; IntPtr port = IntPtr.Zero;
38 
39             //list to hold the returned port names
40             List<string> ports = new List<string>();
41 
42             //new PORT_INFO_2 for holding the ports
43             PORT_INFO_2[] portInfo = null;
44 
45             //enumerate through to get the size of the memory we need
46             result = EnumPorts("", 2, buffer, 0, ref needed, ref cnt);
47             try
48             {
49 
50 
51                 //allocate memory
52                 buffer = Marshal.AllocHGlobal(Convert.ToInt32(needed + 1));
53 
54                 //get list of port names
55                 result = EnumPorts("", 2, buffer, needed, ref needed, ref cnt);
56 
57                 //check results, if 0 (zero) then we got an error
58                 if (result != 0)
59                 {
60                     //set port value
61                     port = buffer;
62 
63                     //instantiate struct
64                     portInfo = new PORT_INFO_2[cnt];
65 
66                     //now loop through the returned count populating our array of PORT_INFO_2 objects
67                     for (int i = 0; i < cnt; i++)
68                     {
69                         portInfo[i] = (PORT_INFO_2)Marshal.PtrToStructure(port, typeof(PORT_INFO_2));
70                         port = (IntPtr)(port.ToInt32() + Marshal.SizeOf(typeof(PORT_INFO_2)));
71                     }
72                     port = IntPtr.Zero;
73                 }
74                 else
75                     throw new Win32Exception(Marshal.GetLastWin32Error());
76 
77                 //now get what we want. Loop through al the
78                 //items in the PORT_INFO_2 Array and populate our generic list
79                 for (int i = 0; i < cnt; i++)
80                 {
81                     ports.Add(portInfo[i].pPortName);
82                 }
83 
84                 //sort the list
85                 ports.Sort();
86                 return ports;
87             }
88             finally
89             {
90                 if (buffer != IntPtr.Zero)
91                 {
92                     Marshal.FreeHGlobal(buffer);
93                     buffer = IntPtr.Zero;
94                     port = IntPtr.Zero;
95 
96                 }
97             }
98         }
99     }

 

posted on 2016-01-05 16:59  JustYong  阅读(1368)  评论(0编辑  收藏  举报