Performance counter throws SecurityException

。_饼干妹妹 提交于 2019-12-11 23:22:44

问题


This is the code:

    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");
    }

Obviously:

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

is the line where the exception was thrown.

I have read about PerformanceCounterPermission, what should I do exactly?


回答1:


Your application's process does not have the appropriate privilege level. That's what the security exception is telling you.

The simple fix is to request that permission when your application starts. You can do this by modifying your application's manifest such that the requestedExecutionLevel is set to requireAdministrator.

The complete section added to your application's manifest will look something like this:

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

There are potentially better alternatives if your application does not otherwise require administrative privileges, because you should always run at the lowest privilege level that is absolutely necessary or required. You can investigate these alternatives using Google; it's going to involve spinning off a separate process that requests UAC elevation and runs the performance counter when requested explicitly by the user.



来源:https://stackoverflow.com/questions/8982304/performance-counter-throws-securityexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!