.NET Windows 服务调用 winspool.Drv 访问被拒绝

.NET Windows Service call winspool.Drv access is denied

我有一个用 C# 编写的 Windows 服务。调用winspool.drv的OpenPrinter方法打开局域网

的打印机时异常

问题只出现在 Windows 7 (x64) 上。当我 运行 使用与 Windows 7 (x64) 上的桌面应用程序相同的服务代码时,它工作正常。

var deviceName = "\ip\printername";
IntPtr hPrinter =new IntPtr();
var  DesiredAccess = PrinterAccessRights.PRINTER_ACCESS_USE | PrinterAccessRights.READ_CONTROL;
bool bRet = SpoolerApi.OpenPrinter(DeviceName, ref hPrinter, new PRINTER_DEFAULTS(DesiredAccess));

System.ComponentModel.Win32Exception (0x80004005): Access is denied

可能是用户问题。尝试更改服务的用户 运行(来自服务控制管理器),也许只是为了测试,您可以将服务 运行 作为您的用户。 如果可行,您可能应该更改打印机的配置方式,以便 运行 用户可以使用该服务,或者创建一个自定义用户 运行 具有打印机访问权限的服务。