Create / open directory with creadentials in Windows - c#

I want create directory with Active directory user credentials, only that user has access for directory manipulation like opening listing files, reading files etc.
public void CreateDirectory(int value)
{
string drive = Directory.GetDirectoryRoot(HostingEnvironment.ApplicationPhysicalPath);
string path = "D://" + "4524l";
DirectoryInfo dinfo = Directory.CreateDirectory(path);
string domainAndUsername = "456456.com" + #"\" + "guserone";
DirectoryEntry entry = new DirectoryEntry("LDAP://124.com", domainAndUsername, "a55in123*");
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + "guserone" + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
DirectorySecurity myDirectorySecurity = dinfo.GetAccessControl();
//myDirectorySecurity.SetOwner(newUser);
myDirectorySecurity = RemoveExplicitSecurity(myDirectorySecurity);
dinfo.SetAccessControl(myDirectorySecurity);
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(domainAndUsername,
FileSystemRights.FullControl, AccessControlType.Allow));
dinfo.SetAccessControl(myDirectorySecurity);
myDirectorySecurity.SetAccessRuleProtection(true, false);
}
private static DirectorySecurity RemoveExplicitSecurity(DirectorySecurity directorySecurity)
{
AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in rules)
directorySecurity.RemoveAccessRule(rule);
return directorySecurity;
}

Assuming you are dealing with a simple scenario, you are probably looking for Directory.CreateDirectory(string path, DirectorySecurity directorySecurity), which you can find documented here.
There's a decent example there that includes creation of basic access controls.

Related

I want w3wp.exe process to access a specific folder

i am working on a project that requires a folder to be accessed by only w3wp.exe process.
no other user can access this folder on the machine
i am working on a console project my implementation so far is
public static void SetFolderPermission(string folderPath){
bool exists = Directory.Exists(folderPath);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(folderPath);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
var directoryInfo = new DirectoryInfo(folderPath);
var directorySecurity = directoryInfo.GetAccessControl();
var currentUserIdentity = GetIISProcessID("w3wp");
//WindowsIdentity.GetCurrent();
var fileSystemRule = new FileSystemAccessRule(currentUserIdentity,
FileSystemRights.FullControl,
InheritanceFlags.ObjectInherit |
InheritanceFlags.ContainerInherit,
PropagationFlags.None,
AccessControlType.Allow);
directorySecurity.AddAccessRule(fileSystemRule);
directoryInfo.SetAccessControl(directorySecurity);
}
and getting the process is
public static int GetIISProcessID(string appPoolName)
{
//return 0;
string commandLine = String.Empty;
Process[] pCollection = Process.GetProcessesByName(appPoolName);
//Process.GetProcessById(7684, "w3wp.exe");
//Process.GetProcessesByName("w3wp.exe");
foreach (Process pInstance in pCollection)
{
ObjectQuery sq = new ObjectQuery
("Select CommandLine from Win32_Process Where ProcessID = '" + pInstance.Id + "'");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq))
{
ManagementObjectCollection objectCollection = searcher.Get();
foreach (ManagementObject oReturn in objectCollection)
{
commandLine = oReturn["CommandLine"].ToString(); break;
}
Console.WriteLine(commandLine);
}
}
return 0;
}
can someone help me figuring out this how can i make a process access a folder.

Query Active Directory using DistinguishedName

I have an application that uses Windows authentication and I am trying to get logged in users info using their domain IDs.
Part of the data returned is the user's manager's DN (in manager property). I need to query AD again to get manager's info (domain id, email, name, etc.).
I searched and can't find any hint of what I have to use in my filter.
This is what I am using and I always get null returned:
private static DirectoryEntry GetUserDEByDN(string sDN)
{
using (HostingEnvironment.Impersonate())
{
PrincipalContext pc = new PrincipalContext(ContextType.Domain, adUSADomain, adUSAContainer);
//UserPrincipal up = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, UserID);
UserPrincipal qbeUser = new UserPrincipal(pc);
//qbeUser.SamAccountName = UserID.Trim().ToUpper();
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
PrincipalSearchResult<Principal> psr = srch.FindAll();
string sDomain = ConfigurationManager.AppSettings["Domain"].ToString();
string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();
DirectoryEntry de = new DirectoryEntry(adPath);
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user)(| (cn = " + sDN + ")(dn = " + sDN + ")))";
//deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserID + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();
if (null != results)
{
de = new DirectoryEntry(results.Path);
return de;
}
else
{
return null;
}
}
}
Is it possible to search Active Directory by DN? If so, what I am doing wrong?
This is what worked for me. However, I believe it is supposed to work with objectClass=user but I kept getting null returned. When I changed to distinguishedName = sDN, it worked.
The whole point of this code
DirectoryEntry de = new DirectoryEntry(adPath + "/" + sDN);
is to start the directory search at the user object; there shouldn’t be the need for the additional search of saying which distinguishedName.
private static DirectoryEntry GetUserDEByDN(string sDN)
{
string adPath = ConfigurationManager.AppSettings["ADPath"].ToString();
DirectoryEntry de = new DirectoryEntry(adPath + "/" + sDN);
DirectoryEntry deManager = null;
using (DirectorySearcher Search = new DirectorySearcher())
{
Search.SearchRoot = de;
Search.Filter = "(&(distinguishedName=" + sDN + "))";
//Search.Filter = "(objectClass = user)";
Search.SearchScope = SearchScope.Base;
SearchResult Result = Search.FindOne();
if (null != Result)
deManager = Result.GetDirectoryEntry();
}
return deManager;
}

C# Creating directory and setting the permissions

I am trying to use the code below to allow all users be able to modify a folder:
class Program
{
private const string FileName = "test.txt";
private static readonly string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\TEST\\" + FileName;
private static readonly string UserName = Environment.UserDomainName;
static void Main()
{
DirectorySecurity securityRules = new DirectorySecurity();
string dirPath = Path.GetDirectoryName(FilePath);
securityRules.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.Modify, AccessControlType.Allow));
if (dirPath == null) throw new InvalidOperationException("Failure to save local security settings");
if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath, securityRules);
File.WriteAllText(FilePath, "Test test!");
}
}
After I run the code, the Users is added to the folder, but not with any rights assigned. All the read, write, execute etc. all the check boxes are not checked. Except the Special permissions is checked.
How Can I add a folder with all Modify for all users?
You can use the Directory.SetAccessControl().
Example:
DirectoryInfo directory = new DirectoryInfo(#"C:\my\directory");
DirectorySecurity security = directory.GetAccessControl();
security.AddAccessRule(new FileSystemAccessRule(#"MYDOMAIN\JohnDoe",
FileSystemRights.Modify,
AccessControlType.Deny));
directory.SetAccessControl(security);
More details in the msdn.

C#, why I can't add domain user into local group?

Why this code doesn work ? What I want to do is add domain user into local group.
DirectorySearcher srch = new DirectorySearcher(new DirectoryEntry("LDAP://" + "AD1.test.it/DC=test,DC=it"));
srch.Filter = "(&(objectClass=user)(sAMAccountName=testUser))";
SearchResultCollection results = srch.FindAll();
DirectoryEntry de = new DirectoryEntry(results[0].Path);
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });
I get this error: "Exception has been thrown by the target of an invocation."
Simillar code works for adding local user into a local group.
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry de = localMachine.Children.Find("testUser", "user");
DirectoryEntry dComUsersGrp = localMachine.Children.Find("Distributed COM Users", "group");
dComUsersGrp.Invoke("Add", new object[] { de.Path.ToString() });
Thank you very much for any help.
string userPath = string.Format("WinNT://{0}/{1},user", domain, user);
string groupPath = string.Format("WinNT://{0}/{1},group", Environment.MachineName, group);
using (DirectoryEntry group = new DirectoryEntry(groupPath))
{
group.Invoke("Add", userPath);
group.CommitChanges();
}
You need to use WinNT:// ADSI namespace.
You usually have to specify logon credentials to access the directory. Something like:
String domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

get computer from OU

I have a code to get a list of all the computers within a domain.
Now i need to just get the computers which are within a particular OU and not the rest of the machines.
so here is my code to get all the machines from a domain, this works perfectly fine:
DirectoryEntry entry = new DirectoryEntry("LDAP://" + selectDomain);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=computer)");
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult resEnt in mySearcher.FindAll())
{
//"CN=SGSVG007DC"
string ComputerName = resEnt.GetDirectoryEntry().Name;
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0, "CN=".Length);
compList.Add(ComputerName);
}
mySearcher.Dispose();
entry.Dispose();
any suggestions?? thanks.
You just need to add the OU to your directory entry, so instead of taking the root of your domain as being the search path, it takes the domain + OU as being the search path.
See "Enumerating objects in an OU" # http://www.codeproject.com/KB/system/everythingInAD.aspx
I see from your commments that you're having issues here, so let's put this simply - note that this code isn't tested, but should clarify...
string selectDomain = "CN=myCompany,CN=com";
string selectOU = "OU=LosAngeles,OU=America";
DirectoryEntry entry = new DirectoryEntry("LDAP://" + selectOU + "," + selectDomain);
That essentially gives you the string of "LDAP://OU=LosAngeles,OU=America,CN=MyCompany,CN=com" as the new directory entry. You must specify the full LDAP path, not just the OU or the domain.
try to use this Directory entry:
DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://OU={0},{1}", ouName, selectDomain));
i tried all the above.. but it did not work... so this is what i tried and it worked.
i understand this is not the best way but its the only way working for me... any suggestion.. thanks
DirectoryEntry entry = new DirectoryEntry("LDAP://" + selectedDomain);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(objectClass=organizationalUnit)");
mySearcher.SizeLimit = int.MaxValue;
mySearcher.PageSize = int.MaxValue;
foreach (SearchResult temp in mySearcher.FindAll())
{
Global.logger.Debug("OU = " + temp.Properties["name"][0].ToString());
DirectoryEntry ou = temp.GetDirectoryEntry();
DirectorySearcher mySearcher1 = new DirectorySearcher(ou);
mySearcher1.Filter = ("(objectClass=computer)");
mySearcher1.SizeLimit = int.MaxValue;
mySearcher1.PageSize = int.MaxValue;
if (temp.Properties["name"][0].ToString() == selectedOU)
{
foreach (SearchResult resEnt in mySearcher1.FindAll())
{
//"CN=SGSVG007DC"
string ComputerName = resEnt.GetDirectoryEntry().Name;
Global.logger.Debug("ComputerName = " + resEnt.Properties["name"][0].ToString());
if (ComputerName.StartsWith("CN="))
ComputerName = ComputerName.Remove(0, "CN=".Length);
compList.Add(ComputerName);
}
}
mySearcher1.Dispose();
ou.Dispose();
}
mySearcher.Dispose();
entry.Dispose();

Categories

Resources