class Program
{
static void Main(string[] args)
{
const string printerName = "Print to file";
const string portName = "FILE:";
const string driverName = "ZEBRA R110Xi4 300DPI"; PrinterPorts printerPorts = new PrinterPorts(); var portNames = printerPorts.GetPortNames();
//判断端口是否存在
if (!portNames.Contains(portName))
{
Console.WriteLine("{0} port is not existed", portName);
return;
} var driverNames = GetDrivers();
//判断Driver是否存在
if (!driverNames.Contains(driverName))
{
Console.WriteLine("{0} driver is not existed", driverName);
return;
} AddPrinter(printerName, portName, driverName); Console.ReadKey();
} private static void AddPrinter(string printerName, string portName,string printerDriver)
{
try
{
//init Win32_Printer class
var printerClass = new ManagementClass("Win32_Printer"); //create new Win32_Printer object
ManagementObject printerObject = printerClass.CreateInstance(); if (printerObject == null)
{
throw new Exception("printerObject is null");
} printerObject["PortName"] = portName;
//set driver and device names
printerObject["DriverName"] = printerDriver; printerObject["DeviceID"] = printerName; // specify put options: update or create
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOrCreate;
//put a newly created object to WMI objects set
printerObject.Put(options);
}
catch (Exception ex)
{
throw new Exception(String.Format("WMI exception: {0}", ex.Message));
}
} /// <summary>
/// Get's a list of drives installed on the computer
/// </summary>
/// <returns></returns>
private static List<string> GetDrivers()
{
var drivers = new List<string>(); var selectQuery = new SelectQuery("Win32_PrinterDriver");
var searcher = new ManagementObjectSearcher(selectQuery); foreach (ManagementObject printerDriver in searcher.Get())
{
// Your code here.
var obj = printerDriver["name"];
string name = string.Empty; if (obj != null)
{
name = obj.ToString().Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[];
} drivers.Add(name);
} return drivers;
} }
     class PrinterPorts
{
//PortType enum
[Flags]
public enum PortType : int
{
write = 0x1,
read = 0x2,
redirected = 0x4,
net_attached = 0x8
} //struct for PORT_INFO_2
[StructLayout(LayoutKind.Sequential)]
public struct PORT_INFO_2
{
public string pPortName;
public string pMonitorName;
public string pDescription;
public PortType fPortType;
internal int Reserved;
} //Win32 API
[DllImport("winspool.drv", EntryPoint = "EnumPortsA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int EnumPorts(string pName, int Level, IntPtr lpbPorts, int cbBuf, ref int pcbNeeded, ref int pcReturned); /// <summary>
/// method for retrieving all available printer ports
/// </summary>
/// <returns>generic list populated with post names (i.e; COM1, LTP1, etc)</returns>
public List<string> GetPortNames()
{
//variables needed for Win32 API calls
int result; int needed = ; int cnt = ; IntPtr buffer = IntPtr.Zero; IntPtr port = IntPtr.Zero; //list to hold the returned port names
List<string> ports = new List<string>(); //new PORT_INFO_2 for holding the ports
PORT_INFO_2[] portInfo = null; //enumerate through to get the size of the memory we need
result = EnumPorts("", , buffer, , ref needed, ref cnt);
try
{ //allocate memory
buffer = Marshal.AllocHGlobal(Convert.ToInt32(needed + )); //get list of port names
result = EnumPorts("", , buffer, needed, ref needed, ref cnt); //check results, if 0 (zero) then we got an error
if (result != )
{
//set port value
port = buffer; //instantiate struct
portInfo = new PORT_INFO_2[cnt]; //now loop through the returned count populating our array of PORT_INFO_2 objects
for (int i = ; i < cnt; i++)
{
portInfo[i] = (PORT_INFO_2)Marshal.PtrToStructure(port, typeof(PORT_INFO_2));
port = (IntPtr)(port.ToInt32() + Marshal.SizeOf(typeof(PORT_INFO_2)));
}
port = IntPtr.Zero;
}
else
throw new Win32Exception(Marshal.GetLastWin32Error()); //now get what we want. Loop through al the
//items in the PORT_INFO_2 Array and populate our generic list
for (int i = ; i < cnt; i++)
{
ports.Add(portInfo[i].pPortName);
} //sort the list
ports.Sort();
return ports;
}
finally
{
if (buffer != IntPtr.Zero)
{
Marshal.FreeHGlobal(buffer);
buffer = IntPtr.Zero;
port = IntPtr.Zero; }
}
}
}

C#添加本地打印机的更多相关文章

  1. AD组策略添加本地账号、设置允许ping回显

    AD组策略添加本地账号 1. 管理工具--组策略管理--选择相应GPO(编辑)----首选项--控制面板设置--本地用户和组--右键添加账号 2.域成员计算机刷新组策略(gpupdate/force) ...

  2. maven添加本地jar包

    今天遇到一个mavan仓库中没有的jar包, 故只能添加本地jar包, 花了不少时间找资料,终于OK.故在此记录. 1. 第一次,在网上看到说可以用<systemPath> 解决, 如下: ...

  3. Sql server之路 (三)添加本地数据库SDF文件

    12月25日 今天搞了半天 添加本地数据库Sdf文件到项目里.总是出现问题. 安装环境 Vs2008 没有安装的环境 1.Vs2008 sp1 2. 适用于 Windows 桌面的 Microsoft ...

  4. [原]逆向iOS SDK -- “添加本地通知”的流程分析

    观点: 代码面前没有秘密 添加通知的 Demo 代码 - (void)scheduleOneLocalNotification { [[UIApplication sharedApplication] ...

  5. maven添加本地依赖包方法

    1.某些情况下不方便上传本地依赖包到Maven repository,可以通过下面方法添加本地依赖包. 2.方法 1).pom.xml中添加以下代码块 <dependency> <g ...

  6. 在Android Studio添加本地aar包引用

    1.如何在Android Studio添加本地aar包引用 https://jingyan.baidu.com/article/2a13832890d08f074a134ff0.html 2.完成上述 ...

  7. Ubuntu Linux系统三种方法添加本地软件库

    闲着没事教教大家以Ubuntu Linux系统三种方法添加本地软件库,ubuntu Linux使用本地软件包作为安装源——转2007-04-26 19:47新手重新系统的概率很高,每次重装系统后都要经 ...

  8. maven添加本地jar到本地库中

    maven添加本地jar到本地库中(用于远端地址下载不了的情况) 在dos命令行执行以下命令将会吧ojdbc14-10.2.0.4.0.jar添加到本地库中(ps:必须已经安装了,maven,并配置了 ...

  9. intelliJ IDEA 怎么添加本地的idea web项目

    概述:这篇文章主要讲述idea开发工具怎么添加本地的idea web项目. 一:首先介绍一下idea web项目的目录结构: 上图详细简单的说了一下idea web项目的文件情况. 二:说明一下部署本 ...

随机推荐

  1. 企业SVN版本管理与代码上线方案

    1.SVN服务实战 1) 什么是SVN(Subversion)? Svn(subversion)是近年来崛起的非常优秀的版本管理工具,与CVS管理工具一样,SVN是一个跨平台的开源的版本控制系统.Sv ...

  2. 如何制作 Ubuntu 系统的 USB 启动盘

    下载 Ubuntu 打开 http://mirrors.ustc.edu.cn 获取安装镜像 --> 获取 ISO 刻录 Ubuntu 到 U 盘 打开 http://rufus.akeo.ie ...

  3. Struts2获取Servlet的api的两种方式,解决ParameterAware过时的问题

    servlet API通过ActionContext进行获取 Struts2对HttpServletRequest,HttpSession和ServletContext进行了封装,构造了3个Map对象 ...

  4. 成都Uber优步司机奖励政策(3月14日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  5. Java编辑环境搭建

    1.Java开发环境搭建 这里主要说的是在Windows系统下的环境搭建 JDK的安装 java的sdk简称JDK ,去其官方网站下载最近的JDK即可http://www.oracle.com/tec ...

  6. CF 600 E. Lomsat gelral

    E. Lomsat gelral http://codeforces.com/contest/600/problem/E 题意: 求每个子树内出现次数最多的颜色(如果最多的颜色出现次数相同,将颜色编号 ...

  7. 怎样安装JMeter

    JMeter有图形界面, 而且支持中文! JMeter官网地址: http://jmeter.apache.org/ 点击左上角的下载: 点击下面的.zip后缀的压缩包: 解压到本地: JMeter目 ...

  8. CSP201412-2:Z字形扫描

    引言:CSP(http://www.cspro.org/lead/application/ccf/login.jsp)是由中国计算机学会(CCF)发起的"计算机职业资格认证"考试, ...

  9. POJ 2449 Remmarguts' Date(第k短路のA*算法)

    Description "Good man never makes girls wait or breaks an appointment!" said the mandarin ...

  10. HDU 3726 Graph and Queries(平衡二叉树)(2010 Asia Tianjin Regional Contest)

    Description You are given an undirected graph with N vertexes and M edges. Every vertex in this grap ...