2012-01-24 177 views
0

这是代码:性能计数器抛出抛出:SecurityException

private static void CreateCounter() 
    { 
     if (PerformanceCounterCategory.Exists("DemoCategory")) 
      PerformanceCounterCategory.Delete("DemoCategory"); 

     CounterCreationDataCollection ccdArray = new CounterCreationDataCollection(); 

     CounterCreationData ccd = new CounterCreationData(); 
     ccd.CounterName = "RequestsPerSecond"; 
     ccd.CounterType = PerformanceCounterType.NumberOfItems32; 
     ccd.CounterHelp = "Requests per second"; 
     ccdArray.Add(ccd); 

     PerformanceCounterCategory.Create("DemoCategory", "Demo category", 
      PerformanceCounterCategoryType.SingleInstance, ccdArray); 

     Console.WriteLine("Press any key, to start use the counter"); 
    } 

很明显:

PerformanceCounterCategory.Create("DemoCategory", "Demo category", 
    PerformanceCounterCategoryType.SingleInstance, ccdArray); 

就是抛出异常的线。

我已阅读约PerformanceCounterPermission,我该怎么办?

+0

修改您的应用程序的清单,使'requestedExecutionLevel'设置为'requireAdministrator'。 –

+0

@CodyGray已解决。谢谢;) –

+1

不客气。增加了一个完整的答案(现在我不再使用手机了!),以便您可以接受并解决问题。 –

回答

6

您的应用程序的进程没有适当的权限级别。这就是安全例外告诉你的。

简单的修复方法是在您的应用程序启动时请求该权限。您可以通过修改应用程序的清单来执行此操作,以使requestedExecutionLevel设置为requireAdministrator

完整的部分添加到您的应用程序的清单将是这个样子:

<!-- Identify the application security requirements. --> 
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
    <security> 
    <requestedPrivileges> 
     <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 
    </requestedPrivileges> 
    </security> 
</trustInfo> 

有可能更好的选择,如果您的应用程序不会否则需要管理员权限,因为你应该以最低的始终运行绝对必要或必需的特权级别。您可以使用Google调查这些替代方案;它将涉及分离单独的进程,该进程请求UAC提升并在用户明确请求时运行性能计数器。

相关问题