Solved

c# Create users home drive

Posted on 2010-08-16
5
643 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
  • 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 500 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

Join & Write a Comment

Disabling the Directory Sync Service Account in Office 365 will stop directory synchronization from working.
Synchronize a new Active Directory domain with an existing Office 365 tenant
This tutorial will walk an individual through the process of transferring the five major, necessary Active Directory Roles, commonly referred to as the FSMO roles to another domain controller. Log onto the new domain controller with a user account t…
This tutorial will walk an individual through the process of configuring their Windows Server 2012 domain controller to synchronize its time with a trusted, external resource. Use Google, Bing, or other preferred search engine to locate trusted NTP …

744 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now