Solved

c# Create users home drive

Posted on 2010-08-16
5
697 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 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

Featured Post

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
Uncontrolled local administrators groups within any organization pose a huge security risk. Because these groups are locally managed it becomes difficult to audit and maintain them.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
There are cases when e.g. an IT administrator wants to have full access and view into selected mailboxes on Exchange server, directly from his own email account in Outlook or Outlook Web Access. This proves useful when for example administrator want…

687 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