Setting User Permission to folder

Step 1 and 2 :

1. Check whether username is exits or not
2. Create username if username not exits




AddUser(@"C:\\Test3", "Tuser5", "F#4H11u>14");


private System.DirectoryServices.DirectoryEntry ActiveDirectory
{
get
{
if (objActive != null)
return objActive;
else
{
objActive = new System.DirectoryServices.DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
return objActive;
}
}
}

public void AddUser(string folderPath, string userName, string password)
{

System.DirectoryServices.DirectoryEntry objUser = null;

try
{
objUser = ActiveDirectory.Children.Find(userName, "user");
}
catch
{
}

if (objUser == null)
{
objUser = ActiveDirectory.Children.Add(userName, "user");
objUser.CommitChanges();
objUser.Invoke("Put", new object[] { "Description", "Created by Gnana Prakash for Demo Project " });
objUser.CommitChanges();
objUser.Invoke("SetPassword", new object[] { password });





//password never expires prop set ..
int flags = 0x10000;
objUser.Invoke("Put", new object[] { "UserFlags", flags });

objUser.CommitChanges();
objUser.RefreshCache();

objUser = null;

SetSecurity(folderPath, userName);
}
}








step3:

Set Permission to folder



public void SetSecurity(string folderPath, string userName)
{
DirectoryInfo objDirectoryInfo = null;
DirectorySecurity objDirectorySecurity = null;
FileSystemAccessRule objRule = null;
try
{
objDirectoryInfo = new DirectoryInfo(folderPath);
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);

//NTAccount objIdentity = new NTAccount(Environment.MachineName + @"\" + userName);
//System.Security.Principal.SecurityIdentifier objk = (SecurityIdentifier)objIdentity.Translate(typeof(SecurityIdentifier));

objDirectorySecurity = objDirectoryInfo.GetAccessControl();
objRule = new FileSystemAccessRule( userName,
FileSystemRights.ReadPermissions,
AccessControlType.Allow);
objDirectorySecurity.AddAccessRule(objRule);




objDirectoryInfo.SetAccessControl(objDirectorySecurity);
label1.Visible = true;
}
finally
{
objDirectoryInfo = null;
objDirectorySecurity = null;
objRule = null;
}

}


Attachments

  • SampleProject (28660-25713-FTPApplication.zip)
  • Comments

    Author: D.Jeya kumar(JK)25 May 2009 Member Level: Gold   Points : 1

    Hi,


    Good sample code. please explain it so that every one will understand easily

    Regards
    JK

    Author: Gnana Prakash 26 May 2009 Member Level: Gold   Points : 0

    Hi jeyakumar

    I will try to put explanation on coming week.

    Guest Author: Everth12 Sep 2012

    Sir, if I have a folder that I want to share and at the same time to add a user with access to my folder, as I do that?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: