拒绝访问试图在C#中清除打印队列 [英] Access Denied trying to purge printqueue in C#

查看:809
本文介绍了拒绝访问试图在C#中清除打印队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#中的方法清空打印队列中的所有项目。下面是我的代码:

I'm trying to make a method in C# that empties all items in a print queue. Below is my code:

LocalPrintServer localPrintServer = new LocalPrintServer(PrintSystemDesiredAccess.AdministratePrinter); 
PrintQueue printQueue = localPrintServer.GetPrintQueue(printerName);

if (printQueue.NumberOfJobs > 0)
{
    printQueue.Purge();
}

在此代码运行,在localPrintServer构造,应用程序引发此错误:
的一个例外,而创建打印服务器对象时出现Win32错误:访问被拒绝

When this code runs, on the localPrintServer constructor, the app throws this error: "An exception occurred while creating the PrintServer object. Win32 error: Access is denied."

这是构造函数有几个重载(包括发送无参数)。尝试任何这些,我拿过去那行,但是当我到达printQueue.Purge()调用,我得到相同的访问被拒绝的消息上面列出。

That constructor has a few overloads (including sending no parameters). Trying any of those, I get past that line, but when I get to the printQueue.Purge() call, I get the same access denied message as listed above.

寻找如何/我能做些什么来解决这个问题的建议。我可以手动从我的电脑中删除打印作业。我不知道如果应用程序具有相同的访问我也没怎么检查运行。

Looking for suggestions of how / what I can do to get around this. I can manually delete the print jobs from my computer. I'm not sure if the app runs with the same access I have nor how to check that.

推荐答案

此问题是由 GetPrintQueue 方法是稍微邪恶造成的,因为它不会让你在需要的访问级别通过。与您的代码,因为它是您连接到打印的服务器的使用 AdministratePrinter 的权利(这是没有意义的),并连接到打印的队列的默认用户权限。因此,操作会失败,即使的每个人的对打印队列管理权限。

This problem is caused by the GetPrintQueue method being slightly evil, since it does not allow you to pass in the desired access level. With your code as it is, you are connecting to the print server with AdministratePrinter rights (which is meaningless), and connecting to the print queue with default user rights. Thus, the operation will fail, even if Everyone has admin rights on the print queue.

要解决此问题,使用构造打印队列而不是指定正确的访问级别:使用(打印服务器PS =新

To fix this, use the constructor for PrintQueue instead to specify the correct access level:

using (PrintServer ps = new PrintServer()) {
    using (PrintQueue pq = new PrintQueue(ps, printerName,
          PrintSystemDesiredAccess.AdministratePrinter)) {
        pq.Purge();
    }
}

这还可能会导致权限错误,如果你不在管理员组的成员的上下文中运行(或不与提升的权限运行),因此用try / catch块围绕这是生产代码是个好主意。

This may still cause permission errors if you're not running in the context of a member of the Administrators group (or not running with elevated permissions), so surrounding this with a try/catch block is a good idea for production code.

这篇关于拒绝访问试图在C#中清除打印队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆