C # WinForm permissions judgment and processing for folders

Source: Internet
Author: User

The WindowsIdentity class can get the identity information of the current performer

[CSharp]View PlainCopy
  1. <summary>
  2. Recursive search File method
  3. </summary>
  4. <param name= "path" > Search directory </param>
  5. <param name= "name" > Search filename </param>
  6. Public void Getdir (string path,string name)
  7. {
  8. DirectoryInfo di = new DirectoryInfo (path);
  9. directorysecurity s = new directorysecurity (path, accesscontrolsections.access);
  10. //Determine if the directory can be accessed
  11. if (!s.areaccessrulesprotected)
  12. {
  13. foreach (DirectoryInfo d in di. GetDirectories ())
  14. {
  15. foreach (FileInfo fi in di. GetFiles ())
  16. {
  17. if (FI. Name.contains (name))
  18. {
  19. Txtinfo.appendtext ("file name:" +fi. Name + "path:" + fi.  FullName + "\ n");
  20. }
  21. }
  22. Getdir (d.fullname, name);
  23. }
  24. }
  25. }

Execute identity permissions on executed programs

If the program is not running as an administrator, the action local file prompts: System.UnauthorizedAccessException exception

Vista and Windows 7 operating systems in order to enhance security, the mechanism of UAC (user Account Control) is increased, and if UAC is turned on, even if the user is logged on with administrator rights, its application will not be able to write to the system directory, the system registry, and other settings that may affect the system's operation by default. This mechanism greatly enhances the security of the system, but for the application developer, we cannot force the user to turn off UAC, but sometimes the application we develop needs to run in Administrator mode, that is, Win7 as Administrator. So how do we implement such a function?

When we run some installers under Win7, we find that we first pop up a dialog box to let the user know if they agree to allow this program to change your computer configuration, but the application we write does not pop up this prompt or run with administrator privileges. This article describes how C # programs are set up to prompt the user to run with administrator privileges.

First add a application Manifest File to the project


The default configuration is as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<asmv1:assembly manifestversion= "1.0" xmlns= "URN:SCHEMAS-MICROSOFT-COM:ASM.V1"
xmlns:asmv1= "Urn:schemas-microsoft-com:asm.v1" xmlns:asmv2= "Urn:schemas-microsoft-com:asm.v2"
xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" >
<assemblyidentity version= "1.0.0.0" name= "Myapplication.app"/>
<trustinfo xmlns= "Urn:schemas-microsoft-com:asm.v2" >
<security>
<requestedprivileges xmlns= "Urn:schemas-microsoft-com:asm.v3" >
<!--UAC Manifest Options
If you want to change the Windows User account Control level replace the
requestedExecutionLevel node with one of the following.

<requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/>
<requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/>
<requestedexecutionlevel level= "Highestavailable" uiaccess= "false"/>

If you want to utilize File and Registry virtualization for backward
Compatibility then delete the requestedExecutionLevel node.
-
<requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/>
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>

We can see that there is a requestedExecutionLevel entry in this configuration that configures the execution permission level for the current application request. This entry has 3 values to choose from, as shown in the following table:

Value Description Comment
AsInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
Highestavailable The application runs with the highest privileges the current user can obtain. Recommended for Mixed-mode applications. Plan to refractor the application in a future release.
Requireadministrator The application runs only for administrators and requires the application is launched with the full access token of a N Administrator. Recommended for administrator only applications. Internal elevation points is not needed. The application is already running elevated.

AsInvoker: If you choose this, the application is running with the current permissions.

Highestavailable: This is run with the highest privileges available to the current user.

Requireadministrator: This is only run with system administrator privileges.

By default, it is AsInvoker.

Both the highestavailable and Requireadministrator options can prompt the user for system administrator privileges. So what's the difference between these two options?

The difference is that if we are not logged in as an administrator account, then if the application is set to Requireadministrator, then the application will fail to run directly and cannot start. If set to Highestavailable, the application can run successfully, but runs with the permissions of the current account instead of system administrator privileges. If we want the program to run when a non-admin account is logged in (in which case some functionality should be limited), we recommend that you configure it with highestavailable.

Please refer to the following links for authoritative documentation on requestedExecutionLevel settings:

Create and Embed an application Manifest (UAC)

The following is the modified configuration file:

<?xml version= "1.0" encoding= "Utf-8"?>
<asmv1:assembly manifestversion= "1.0" xmlns= "URN:SCHEMAS-MICROSOFT-COM:ASM.V1"
xmlns:asmv1= "Urn:schemas-microsoft-com:asm.v1" xmlns:asmv2= "Urn:schemas-microsoft-com:asm.v2"
xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" >
<assemblyidentity version= "1.0.0.0" name= "Myapplication.app"/>
<trustinfo xmlns= "Urn:schemas-microsoft-com:asm.v2" >
<security>
<requestedprivileges xmlns= "Urn:schemas-microsoft-com:asm.v3" >
<!--UAC Manifest Options
If you want to change the Windows User account Control level replace the
requestedExecutionLevel node with one of the following.

<requestedexecutionlevel level= "AsInvoker" uiaccess= "false"/>
<requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/>
<requestedexecutionlevel level= "Highestavailable" uiaccess= "false"/>

If you want to utilize File and Registry virtualization for backward
Compatibility then delete the requestedExecutionLevel node.
-
<requestedexecutionlevel level= "Requireadministrator" uiaccess= "false"/>
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly> configuration file Modification, we run the application, we will first pop up a prompt box, click Yes, the program can continue to run, and get the privileges of the system administrator.


Let's take a look at how the program knows if it is currently running on system administrator or non-system administrator rights:
Using System.Security.Principal

public static bool Isadministrator ()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent ();
WindowsPrincipal principal = new WindowsPrincipal (identity);
return principal. IsInRole (Windowsbuiltinrole.administrator);
This code can be used to determine whether the current program is running under System administrator privileges. If configured as AsInvoker, this function returns false under Win7, and returns True if it is requireadministrator.

Using System;
Using System.Collections;
Using System.IO;
Using System.Security.AccessControl;
Static Class Tester
{


public static void Main ()
{
Try
{
string filename = @ "f:\k"; Target directory
String account = @ "Administrator";//user name
String userrights = @ "RW";//permission string, self-defined
Adddirectorysecurity (filename, account, userrights);
Console.ReadLine ();
}
catch (Exception e)
{
Console.WriteLine (e);
Console.ReadLine ();
}
}


static public void Adddirectorysecurity (string FileName, String account, String userrights)
{
filesystemrights rights = new Filesystemrights ();


if (Userrights.indexof ("R") >= 0)
{
Rights = Rights | Filesystemrights.read;
}
if (Userrights.indexof ("C") >= 0)
{
Rights = Rights | Filesystemrights.changepermissions;
}
if (Userrights.indexof ("F") >= 0)
{
Rights = Rights | Filesystemrights.fullcontrol;
}
if (Userrights.indexof ("W") >= 0)
{
Rights = Rights | Filesystemrights.write;
}


BOOL OK;
DirectoryInfo dInfo = new DirectoryInfo (FileName);
DirectorySecurity dsecurity = Dinfo.getaccesscontrol ();
InheritanceFlags iflags = new InheritanceFlags ();
IFlags = Inheritanceflags.containerinherit | Inheritanceflags.objectinherit;
FileSystemAccessRule AccessRule2 = new FileSystemAccessRule (account, rights, IFlags, Propagationflags.none, Accesscontroltype.allow);
Dsecurity.modifyaccessrule (Accesscontrolmodification.add, AccessRule2, out OK);


Dinfo.setaccesscontrol (dsecurity);


List the permissions that the destination directory has
DirectorySecurity sec = Directory.getaccesscontrol (FileName, Accesscontrolsections.all);
foreach (FileSystemAccessRule rule in sec. Getaccessrules (True, True, typeof (System.Security.Principal.NTAccount)))
{
Console.WriteLine ("----------------------------------");
Console.WriteLine (rule. Identityreference.value);
if (rule. Filesystemrights & filesystemrights.read)! = 0)
Console.WriteLine (rule. Filesystemrights.tostring ());
}
Console.read ();
}
}

C # WinForm permissions judgment and processing for folders

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.