检查我的应用程序是否有权读取进程信息以及读/写文件和目录

发布于 2024-12-07 17:08:30 字数 63 浏览 1 评论 0原文

如何检查我的 C# 应用程序是否具有获取进程列表、终止进程、获取目录、获取目录中的文件、读写文件等的权限?谢谢!

How to check in my C# application if I have Permissions to get process list, kill processes, get directories, get files in directories, read and write files and etc? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩心态 2024-12-14 17:08:30

如果您有权限可以毫无问题地执行操作,如果缺乏权限,您可以捕获异常并处理它(UnauthorizedAccessException 等)。

If your has permission can do the operation without issue, if there is a lack of permission you can catch the exception and handle it(UnauthorizedAccessException etc).

萌能量女王 2024-12-14 17:08:30

在 .NET 中,有两种方法可以做到这一点。

System.Security.Permissions 命名空间 具有您需要的属性和类。您可以使用属性并编写声明性代码,或者将类与命令式代码一起使用。

例如,对于 FileIO,您可以执行以下操作

声明式
通常,您会根据 SecurityAction 当前或调用代码没有所述权限时抛出异常

[FileIOPermissionAttribute(SecurityAction.PermitOnly, 
           ViewAndModify = "C:\\example\\sample.txt")]

命令:在这里您可以以编程方式检查对于

FileIOPermission f = new FileIOPermission(PermissionState.None);
f.AllLocalFiles = FileIOPermissionAccess.Read;
try
{
  f.Demand();
}
catch (SecurityException s)
{
  Console.WriteLine(s.Message);
}

命令式或声明式权限,您的代码必须对异常做出反应。 SecurityAction 枚举解释了它们的工作原理,一些检查当前代码是否有权限,有些也检查调用代码。该枚举具有相同的相应方法(Deny、Assert 等),可在命令式代码中使用。

最后,System.Security.Permissions 命名空间 没有任何内容进程,所以我假设你不能真正在这里检查权限。尽管它适用于 .NET 1.1 这篇安全文章 非常相关。 (虽然没有彩色代码=(

In .NET there are two ways to do this.

The System.Security.Permissions namespace has attributes and classes you need. You can use the attributes and write declarative code, or use the classes with imperative code.

As an example, for FileIO you would do this

Declarative :
Typically you annotate a method, and based on the SecurityAction exceptions are thrown is the current or calling code doesn't have the said permission

[FileIOPermissionAttribute(SecurityAction.PermitOnly, 
           ViewAndModify = "C:\\example\\sample.txt")]

Imperative: Here you can programatically check for permissions

FileIOPermission f = new FileIOPermission(PermissionState.None);
f.AllLocalFiles = FileIOPermissionAccess.Read;
try
{
  f.Demand();
}
catch (SecurityException s)
{
  Console.WriteLine(s.Message);
}

Imperative or declarative, your code has to react to an exception. The SecurityAction enum explains how these work, some check if the current code has permission, some check the calling code too. This enum has the same corresponding methods (Deny,Assert,etc) which can be used in imperative code.

Lastly, the System.Security.Permissions namespace doesn't have anything for processes, so I assume you can't really check for permissions here. Although it's for .NET 1.1 this security article is pretty relevant. (Doesn't have coloured code though =(

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文