Set user access permissions for a directory of Windows system NTFS (C #)

Source: Internet
Author: User
Tags foreach bool tostring
window| access using System;

Using System.Drawing;

Using System.Collections;

Using System.ComponentModel;

Using System.Windows.Forms;

Using System.Data;

Using System.Management;

Using System.Text;

Using System.Runtime.InteropServices;

Namespace SetACL

{

<summary>

Summary description of the Form1.

</summary>

public class Form1:System.Windows.Forms.Form

{

Private System.Windows.Forms.TextBox TextBox1;

Private System.Windows.Forms.TextBox TextBox2;

Private System.Windows.Forms.Button SetACL;

Private System.Windows.Forms.Label Label1;

Private System.Windows.Forms.Label Label2;

Private System.Windows.Forms.Button button1;

<summary>

The required designer variable.

</summary>

Private System.ComponentModel.Container components = null;



Public Form1 ()

{

//

Required for Windows Forms Designer support

//

InitializeComponent ();



//

TODO: Add any constructor code after the InitializeComponent call

//

}



<summary>

Clean up all resources that are in use.

</summary>

protected override void Dispose (bool disposing)

{

if (disposing)

{

if (Components!= null)

{

Components. Dispose ();

}

}

Base. Dispose (disposing);

}



#region Windows Form Designer generated code

<summary>

Designer supports required methods-do not use the Code editor to modify

The contents of this method.

</summary>

private void InitializeComponent ()

{

This.textbox1 = new System.Windows.Forms.TextBox ();

This.textbox2 = new System.Windows.Forms.TextBox ();

This. SetACL = new System.Windows.Forms.Button ();

This.label1 = new System.Windows.Forms.Label ();

This.label2 = new System.Windows.Forms.Label ();

This.button1 = new System.Windows.Forms.Button ();

This. SuspendLayout ();

//

TextBox1

//

This.textBox1.Location = new System.Drawing.Point (80, 32);

This.textBox1.Name = "TextBox1";

This.textBox1.Size = new System.Drawing.Size (152, 21);

This.textBox1.TabIndex = 0;

This.textBox1.Text = "C:\\test";

//

TextBox2

//

This.textBox2.Location = new System.Drawing.Point (80, 80);

This.textBox2.Name = "TextBox2";

This.textBox2.Size = new System.Drawing.Size (152, 21);

This.textBox2.TabIndex = 1;

This.textBox2.Text = "ASPNET";

//

SetACL

//

This. Setacl.location = new System.Drawing.Point (152, 136);

This. Setacl.name = "SetACL";

This. Setacl.tabindex = 2;

This. Setacl.text = "Set";

This. Setacl.click + = new System.EventHandler (this. Setacl_click);

//

Label1

//

This.label1.Location = new System.Drawing.Point (24, 80);

This.label1.Name = "Label1";

This.label1.Size = new System.Drawing.Size (48, 23);

This.label1.TabIndex = 5;

This.label1.Text = "User:";

//

Label2

//

This.label2.Location = new System.Drawing.Point (24, 32);

This.label2.Name = "Label2";

This.label2.Size = new System.Drawing.Size (48, 23);

This.label2.TabIndex = 6;

This.label2.Text = "directory:";

//

Button1

//

This.button1.Location = new System.Drawing.Point (8, 168);

This.button1.Name = "Button1";

This.button1.TabIndex = 7;

This.button1.Text = "Button1";

This.button1.Click + = new System.EventHandler (This.button1_click);

//

Form1

//

This. AutoScaleBaseSize = new System.Drawing.Size (6, 14);

This. ClientSize = new System.Drawing.Size (280, 197);

This. Controls.Add (This.button1);

This. Controls.Add (THIS.LABEL2);

This. Controls.Add (THIS.LABEL1);

This. Controls.Add (this. SETACL);

This. Controls.Add (THIS.TEXTBOX2);

This. Controls.Add (This.textbox1);

This. MaximizeBox = false;

This. MinimizeBox = false;

This. Name = "Form1";

This. Text = "Form1";

This. ResumeLayout (FALSE);



}

#endregion



<summary>

The main entry point for the application.

</summary>

[STAThread]

static void Main ()

{

Application.Run (New Form1 ());

}

[DllImport ("advapi32.dll")]

public static extern bool LookupAccountName (string lpsystemname, string lpaccountname,byte[] sid,ref int Cbsid, Stringbui Lder referenceddomainname, ref int cbreferenceddomainname,ref int peuse);



private void Setacl_click (object sender, System.EventArgs e)

{

String Filepath=this.textbox1.text;

String Username=this.textbox2.text;

if (Getfilesystem (filepath.substring (0,1))!= "NTFS")

Return

if (Findtrustee (filepath,username))

Return

SetDacl (Filepath,username);

}

private string Getfilesystem (String diskname)

{

String Filesystem= "";

System.Management.ManagementObjectSearcher diskclass=new managementobjectsearcher ("Select filesystem from Win32_ LogicalDisk where name= ' "+diskname+": ' ");

Managementobjectcollection Disks=diskclass.get ();

foreach (ManagementObject disk in disks)

{

Propertydatacollection Diskproperties=disk. Properties;

foreach (Propertydata diskproperty in diskproperties)

{

FileSystem = diskProperty.Value.ToString ();

}

}

return filesystem;



}

private bool Findtrustee (string filepath,string userName)

{

ArrayList trusteesname=new ArrayList ();

Managementpath path = new Managementpath ();

Path. Server = ".";

Path. NamespacePath = @ "root\cimv2";

Path. RelativePath = @ "Win32_logicalfilesecuritysetting.path= '" +filepath+ ""; Navigate to Folder

ManagementObject dir = new ManagementObject (path);

Managementbaseobject outparams = dir. InvokeMethod ("Getsecuritydescriptor", NULL, NULL); Get Security descriptor



if ((UINT) (outparams.properties["ReturnValue"). Value))!= 0//ok

{

throw new Exception ("Get file descriptor failed");

}

Managementbaseobject descriptor = (managementbaseobject) (outparams.properties["descriptor"). Value));

Managementbaseobject[] Daclobject = (managementbaseobject[]) (descriptor.properties["Dacl"). Value)); Get access Control List

for (int i=0;i<daclobject.length;i++)

{

Trusteesname.add ((Managementbaseobject) daclobject[i]. properties["Trustee"]. Value). properties["Name"]. Value);

}

Return Trusteesname.contains (UserName);

}

private void SetDacl (String filepath,string userName)

{

Get account information

int cbsid = 100;

byte[] UserSID = new BYTE[28];

StringBuilder domainname=new StringBuilder (255);

int domainnamelength = 255;

int sidtype = 255;

BOOL result = LookupAccountName (null, USERNAME,USERSID, ref cbsid, Domainname,ref domainnamelength,ref sidtype);

if (!result)

Return

Get file Descriptor

Managementpath path = new Managementpath ();

Path. Server = ".";

Path. NamespacePath = @ "root\cimv2";

Path. RelativePath = @ "Win32_logicalfilesecuritysetting.path= '" +filepath+ "";

ManagementObject dir = new ManagementObject (path);

Managementbaseobject outparams = dir. InvokeMethod ("Getsecuritydescriptor", NULL, NULL);

if ((UINT) (outparams.properties["ReturnValue"). Value))!= 0)

{

throw new Exception ("Get file descriptor failed");

}

Managementbaseobject descriptor = (managementbaseobject) (outparams.properties["descriptor"). Value));

Get access Control List

Managementbaseobject[] Daclobject = (managementbaseobject[]) (descriptor.properties["Dacl"). Value));



Copy an Access control entry

Managementbaseobject ace= (Managementbaseobject) daclobject[0]. Clone ();



Set access Control Item properties

Managementbaseobject trustee= (managementbaseobject) ace. properties["Trustee"]. Value;

Trustee. properties["Domain". Value=domainname.tostring ();

Trustee. properties["Name"]. Value=username;

Trustee. properties["SID"]. Value=usersid;

Trustee. properties["Sidlength"]. Value=28;//trustee. properties["SidString"]. Value= "s-1-5-21-602162358-708899826-854245398-1005";

Ace. properties["Trustee"]. Value=trustee;

Ace. properties["AccessMask"]. value=2032127;

Ace. properties["AceFlags"]. value=3;

Ace. properties["AceType"]. value=0;

Copy an Access control list and add the access control entries that were generated above to the following.

Managementbaseobject[] Newdacl=new managementbaseobject[daclobject.length+1];

for (int i=0;i<daclobject.length;i++)

{

Newdacl[i]=daclobject[i];

}

Newdacl[daclobject.length]=ace;

Set the DACL property of the security descriptor to the newly generated access control list

descriptor.properties["Dacl"]. Value=newdacl;

Set security descriptor

Dir. Scope.options.enableprivileges=true;

Managementbaseobject Inproperties=dir. Getmethodparameters ("SetSecurityDescriptor");

inproperties["Descriptor"] = descriptor;

Outparams = dir. InvokeMethod ("SetSecurityDescriptor", inproperties, NULL);

}



private void Button1_Click (object sender, System.EventArgs e)

{

System.Management.ManagementObjectSearcher cmicwmi=new System.Management.ManagementObjectSearcher ("SELECT * FROM Win32_baseboard ");

foreach (System.Management.ManagementObject cmicwmiobj in Cmicwmi.get ())

{

Debug.WriteLine ("BIOS serial number" & Cmicwmiobj["SerialNumber"]);

This.textBox1.Text = "BIOS serial number" + cmicwmiobj["product"];

}





}

}

}






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.