Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

c# Create users home drive

Posted on 2010-08-16
5
Medium Priority
?
739 Views
Last Modified: 2012-05-10
Afternoon all!

I need to create users home drives programatically. I have a script which creates all of the users, so for example it does the following:

Create AD account.
Create Home Drive folder
Assign permission to Home Drive
Create Exchange Mailbox

But, when assigning permissions to the Home Drive for that user I get errors saying it can not translate that user etc probably because the users was created about 1 second before it is trying to assign permissions.

Does anyone have any ideas how i should go about this?

 
////////////////////////////////////////////////////////////////////////////
                            // CREATE THE USERS HOME FOLDER
                            //
                            try
                            {
                                // Set the folder path where we want to store the new students home folder
                                //string activeDir = homeDirectory;

                                // the location and what we want the folder name calling
                                //string newPath = System.IO.Path.Combine(activeDir, UserNameFinal);

                                // Create the folder
                                System.IO.Directory.CreateDirectory(homeDirectory);

                                // Log the success
                                Log_Action("Home Folder: Created!");
                            }
                            catch (Exception ex)
                            {
                                // Log the fail
                                Log_Action("Home Folder: Failed -" + ex.ToString());
                            }


/////////////////////////////////////////////////////////////////////////////
                            /// Set folder permission
                            ///
                            try
                            {
                                // Set the folder path where we want to store the new students home folder
                                //string activeDir = homeDirectory;

                                // the location and what we want the folder name calling
                                //string newPath = System.IO.Path.Combine(activeDir, UserNameFinal);

                                try
                                {
                                    // Get the users GUID 
                                  /* string SID = KazooSoft.ActiveDirectoryFunctions.GetObjectSID(
                                       distinguishedName, 
                                       KazooADIntegration.Properties.Settings.Default.LDAP_server + "/" + KazooADIntegration.Properties.Settings.Default.AD_distinguishedName);
                                    */
                                    // User
                                    KazooSoft.FolderPermissions.AddFileSecurity(homeDirectory,
                                        Environment.UserDomainName + "\\" + UserNameFinal,
                                        FileSystemRights.FullControl | FileSystemRights.TakeOwnership,
                                        AccessControlType.Allow);

                                    Log_Action("Permissions: " + UserNameFinal + " Successfull!");
                                }
                                catch (Exception ex)
                                {
                                    Log_Action("Permissions: " + UserNameFinal + " FAILED - " + ex);
                                    
                                }
                                
                                // Log
                                

                                // Domain Admin
                                KazooSoft.FolderPermissions.AddFileSecurity(homeDirectory,
                                    Environment.UserDomainName + "\\Administrator",
                                    FileSystemRights.FullControl,
                                    AccessControlType.Allow);
                                // Log
                                Log_Action("Permissions: " + Environment.UserDomainName + "\\Administrator Successfull!");

                                // Local Admin
                                KazooSoft.FolderPermissions.AddFileSecurity(homeDirectory,
                                    "Administrator",
                                    FileSystemRights.FullControl,
                                    AccessControlType.Allow);
                                Log_Action("Permissions: Local Administrator Successfull!");

                                // Write to the log
                                Log_Action("Permissions: Complete!");
                            }
                            catch (Exception ex)
                            {
                                Log_Action("Permissions: Failed -" + ex.ToString());
                            }

Open in new window

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;

namespace KazooSoft
{
    class FolderPermissions
    {
        // Adds an ACL entry on the specified file for the specified account.
        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {


            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

            

        }

        // Removes an ACL entry on the specified file for the specified account.
        public static void RemoveFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {

            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Remove the FileSystemAccessRule from the security settings.
            fSecurity.RemoveAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }
    }
}

Open in new window

0
Comment
Question by:KazooSoft
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 4

Author Comment

by:KazooSoft
ID: 33446164
I think i may be doing it wrong.

So i have tried this:

        // Adds folder permission
        public static void AddFolderSecurity(string folderName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {
            DirectorySecurity dirSec = Directory.GetAccessControl(folderName);
            dirSec.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
            Directory.SetAccessControl(folderName, dirSec);
        }


But I get an error saying:

16/08/2010 15:40:43: Permissions: Failed -System.IO.DirectoryNotFoundException: \\ncs-srv-fs2\studenthomes$\TESTAREA\FOLDERNAME
   at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext)
   at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory)
   at System.Security.AccessControl.DirectorySecurity..ctor(String name, AccessControlSections includeSections)
   at System.IO.Directory.GetAccessControl(String path)
   at KazooSoft.FolderPermissions.AddFolderSecurity(String folderName, String account, FileSystemRights rights, AccessControlType controlType)
   at KazooSoft.frmMain.CreateAccounts()
0
 
LVL 7

Accepted Solution

by:
jdavistx earned 2000 total points
ID: 33446736
I would try a couple things.

Create a breakpoint where the directory is supposed to be created, run in Debug, and at the point where the directory "should" be created I would manually check the path that is being created via Windows explorer, or some other means that's independent of your program.

Alternatively, if you know the problem is because the directory hasn't been created then I would do something like the attached code.

However, that could be problematic as well.
while(!Directory.Exists(folderName))
   System.Threading.Thread.Sleep(10);

Open in new window

0
 
LVL 4

Author Comment

by:KazooSoft
ID: 33447314
The creation of the directory is the easy part. The problem I am having is assigning the rights for the user which has only just been created in the AD.
0
 
LVL 7

Expert Comment

by:jdavistx
ID: 33447352
Yes, but you had mentioned in your post (and elaborated upon with the runtime exception) that there is a problem when assigning rights to a directory that doesn't exist.

I was suggesting that you only attempt to assign the rights to the directory once your program knows the directory actually exists.
0
 
LVL 4

Author Comment

by:KazooSoft
ID: 33448815
Ahh sorry matr I will post the new errors in the morning.
0

Featured Post

Are your AD admin tools letting you down?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently, Microsoft released a best-practice guide for securing Active Directory. It's a whopping 300+ pages long. Those of us tasked with securing our company’s databases and systems would, ideally, have time to devote to learning the ins and outs…
Microsoft Office 365 is a subscriptions based service which includes services like Exchange Online and Skype for business Online. These services integrate with Microsoft's online version of Active Directory called Azure Active Directory.
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question