none
c# set Directory sharing permission Full control for Everyone programmatically in Windows 7 or Windows Vista

Answers

  • I found the solution.

    1 ) Set Access Control

    DirectoryInfo dInfo = new DirectoryInfo(fileName);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone",FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly,AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
    
    
    

    2) Sharing foldel

    ManagementClass mc = new ManagementClass("win32_share");
    ManagementBaseObject inParams = mc.GetMethodParameters("Create");
    inParams("Description") = "My Shared Folder";
    inParams("Name") = "Shared Folder Name";
    inParams("Path") = "C:\\Folder1";
    inParams("Type") = ShareResourceType.DiskDrive;
    inParams("MaximumAllowed") = null;
    inParams("Password") = null;
    inParams("Access") = null; // Make Everyone has full control access.
    ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
    
    
    

    3) Only in Windows 7 and Vista, upgrade "Everyone" sharing right

    //user selection
    NTAccount ntAccount = new NTAccount("Everyone");
    
    //SID
    SecurityIdentifier userSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
    byte[] utenteSIDArray = new byte[userSID.BinaryLength];
    userSID.GetBinaryForm(utenteSIDArray, 0);
    
    //Trustee
    ManagementObject userTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
    userTrustee["Name"] = "Everyone";
    userTrustee["SID"] = utenteSIDArray;
    
    //ACE
    ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null);
    userACE["AccessMask"] = 2032127;                                 //Full access
    userACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit;
    userACE["AceType"] = AceType.AccessAllowed;
    userACE["Trustee"] = userTrustee;
    
    ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
    userSecurityDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT 
    userSecurityDescriptor["DACL"] = new object[] { userACE };
    
    //UPGRADE SECURITY PERMISSION
    ManagementClass mc = new ManagementClass("Win32_Share");
    ManagementObject share = new ManagementObject(mc.Path + ".Name='" + CondivisionName + "'");
    share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, description, userSecurityDescriptor });
    

    This allow me to upgrade the security permission of "Everyone" in Windows Vista & 7 and get "Full Control".

    It's all correct?

    Can you give me your feedback?


    - Andrea Bianchi - site: http://www.BianchiAndrea.com
    Thursday, February 10, 2011 9:17 AM

All replies

  • Wow, a null ACL is going to grant access to even unauthenticated users, not just everyone on the machine, are you sure you want to do that?

    You probably want to use the classes in System.Security.AccessControl instead of WMI.



    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    Monday, February 07, 2011 6:34 PM
  • Hi Sheng,

    My problem exist only in Windows Vista & 7, not in Windows xp & 2000.

    I already use AccessControl ...

    DirectoryInfo dInfo = new DirectoryInfo(fileName);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone",FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly,AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
    
    

    ... but it allow me to set "Security permission" not "Shared permission". 

    To activate sharing in the directory I use WMI

    ManagementClass mc = new ManagementClass("win32_share");
    ManagementBaseObject inParams = mc.GetMethodParameters("Create");
    inParams("Description") = "My Shared Folder";
    inParams("Name") = "Shared Folder Name";
    inParams("Path") = "C:\\Folder1";
    inParams("Type") = ShareResourceType.DiskDrive;
    inParams("MaximumAllowed") = null;
    inParams("Password") = null;
    inParams("Access") = null; // Make Everyone has full control access.
    ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
    
    

    but if I go in ...

    Directory -> Properties -> Sharing -> Advanced Sharing -> Permission

    ... the Everyone users have only read permission.

    What did I do wrong?

    Thanks again.

     


    - Andrea Bianchi - site: http://www.BianchiAndrea.com
    Tuesday, February 08, 2011 9:25 AM
  • That sounds like a security issue, you need to run your process elevated to do administrative tasks. Search "netsharesetinfo error 5" for more details.

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    Tuesday, February 08, 2011 2:56 PM
  • I use Administrator user, my User Account Control Settings are "Never notify", I "Run As Administrator", but don't work.
    Tuesday, February 08, 2011 3:59 PM
  • No, if your app requires administrative permission, you declare it in requestedExecutionLevel

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    Tuesday, February 08, 2011 4:24 PM
  • I have already declared requestExecutionLevel,

    my .manifest:

    <?xml version="1.0" encoding="utf-8"?>
    <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
     <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
      <security>
       <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
        <!-- UAC Manifest Options
          If you want to change the Windows User Account Control level replace the 
          requestedExecutionLevel node with one of the following.
    
        <requestedExecutionLevel level="asInvoker" uiAccess="false" />
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
        <requestedExecutionLevel level="highestAvailable" uiAccess="false" />
    
          If you want to utilize File and Registry Virtualization for backward 
          compatibility then delete the requestedExecutionLevel node.
        -->
        <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
       </requestedPrivileges>
      </security>
     </trustInfo>
    </asmv1:assembly>
    
    

    - Andrea Bianchi - site: http://www.BianchiAndrea.com
    Wednesday, February 09, 2011 8:33 AM
  • Try netsharesetinfo and call getlasterror to see what the error code is.

    The following is signature, not part of post
    Please mark the post answered your question as the answer, and mark other helpful posts as helpful, so they will appear differently to other users who are visiting your thread for the same problem.
    Visual C++ MVP
    Wednesday, February 09, 2011 5:18 PM
  • I found the solution.

    1 ) Set Access Control

    DirectoryInfo dInfo = new DirectoryInfo(fileName);
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone",FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly,AccessControlType.Allow));
    dInfo.SetAccessControl(dSecurity);
    
    
    

    2) Sharing foldel

    ManagementClass mc = new ManagementClass("win32_share");
    ManagementBaseObject inParams = mc.GetMethodParameters("Create");
    inParams("Description") = "My Shared Folder";
    inParams("Name") = "Shared Folder Name";
    inParams("Path") = "C:\\Folder1";
    inParams("Type") = ShareResourceType.DiskDrive;
    inParams("MaximumAllowed") = null;
    inParams("Password") = null;
    inParams("Access") = null; // Make Everyone has full control access.
    ManagementBaseObject outParams = classObj.InvokeMethod("Create", inParams, null);
    
    
    

    3) Only in Windows 7 and Vista, upgrade "Everyone" sharing right

    //user selection
    NTAccount ntAccount = new NTAccount("Everyone");
    
    //SID
    SecurityIdentifier userSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
    byte[] utenteSIDArray = new byte[userSID.BinaryLength];
    userSID.GetBinaryForm(utenteSIDArray, 0);
    
    //Trustee
    ManagementObject userTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
    userTrustee["Name"] = "Everyone";
    userTrustee["SID"] = utenteSIDArray;
    
    //ACE
    ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null);
    userACE["AccessMask"] = 2032127;                                 //Full access
    userACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit;
    userACE["AceType"] = AceType.AccessAllowed;
    userACE["Trustee"] = userTrustee;
    
    ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
    userSecurityDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT 
    userSecurityDescriptor["DACL"] = new object[] { userACE };
    
    //UPGRADE SECURITY PERMISSION
    ManagementClass mc = new ManagementClass("Win32_Share");
    ManagementObject share = new ManagementObject(mc.Path + ".Name='" + CondivisionName + "'");
    share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, description, userSecurityDescriptor });
    

    This allow me to upgrade the security permission of "Everyone" in Windows Vista & 7 and get "Full Control".

    It's all correct?

    Can you give me your feedback?


    - Andrea Bianchi - site: http://www.BianchiAndrea.com
    Thursday, February 10, 2011 9:17 AM
  • On my try,

    In the Set Access Control,

    dSecurity.AddAccessRule(new FileSystemAccessRule("everyone",FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly,AccessControlType.Allow));

    When PropagationFlags is set to InheritOnly, no NTFS permissions are granted to Everyone role (see folder properties\Security tab)

    After you set it to PropagationFlags

    .NoPropagateInherit, all permissions are granted to Everyone role.

     

     

    Friday, August 05, 2011 4:31 AM
  • Where is CondivisionName declared?  It appears your code is a mashup between C# and VB.

    Friday, April 06, 2012 3:03 PM
  • I was able to get it to work on Win7 - giving full control to Everyone on Security tab, as well as in Permissions of the Sharing tab.

    The "Share" sub will create an apps2 folder (if it doesn't exist) under the folder that the EXE is in, share it, and give Everyone full control. The full control on Sharing/Permissions seems to be needed to access the folder remotely.

            /*
             * This method is used to perform the main actions of sharing the folders
             * It accepts three arguments: -
             * A path of the folder,
             * A ShareName by which you would want to share the folder
             * Description of the folder
             * You cannot have the first two arguments as empty. They should consist of
             * data. The third arguments can be an empty string.
             */
            private static void QshareFolder(string FolderPath, string ShareName, string Description)
            {
                try
                {
                    // Create a ManagementClass object
                    ManagementClass managementClass = new ManagementClass("Win32_Share");

                    // Create ManagementBaseObjects for in and out parameters
                    ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
                    ManagementBaseObject outParams;

                    // Set the input parameters
                    inParams["Description"] = Description;
                    inParams["Name"] = ShareName;
                    inParams["Path"] = FolderPath;
                    inParams["Type"] = 0x0; // Disk Drive
                    //Another Type:
                    //        DISK_DRIVE = 0x0
                    //        PRINT_QUEUE = 0x1
                    //        DEVICE = 0x2
                    //        IPC = 0x3
                    //        DISK_DRIVE_ADMIN = 0x80000000
                    //        PRINT_QUEUE_ADMIN = 0x80000001
                    //        DEVICE_ADMIN = 0x80000002
                    //        IPC_ADMIN = 0x8000003
                    inParams["MaximumAllowed"] = null;
                    inParams["Password"] = null;
                    inParams["Access"] = null; // Make Everyone has full control access.                
                    //inParams["MaximumAllowed"] = int maxConnectionsNum;

                    // Invoke the method on the ManagementClass object
                    outParams = managementClass.InvokeMethod("Create", inParams, null);
                    // Check to see if the method invocation was successful
                    if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                    {
                        //MessageBox.Show ("Unable to share the folder: " + outParams.Properties["ReturnValue"].Value);
                        MessageBox.Show("Error sharing MMS folders. Please make sure you install as Administrator.", "Error!");
                    }

                    //user selection
                    NTAccount ntAccount = new NTAccount("Everyone");

                    //SID
                    SecurityIdentifier userSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
                    byte[] utenteSIDArray = new byte[userSID.BinaryLength];
                    userSID.GetBinaryForm(utenteSIDArray, 0);

                    //Trustee
                    ManagementObject userTrustee = new ManagementClass(new ManagementPath("Win32_Trustee"), null);
                    userTrustee["Name"] = "Everyone";
                    userTrustee["SID"] = utenteSIDArray;

                    //ACE
                    ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null);
                    userACE["AccessMask"] = 2032127;                                 //Full access
                    userACE["AceFlags"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit;
                    userACE["AceType"] = AceType.AccessAllowed;
                    userACE["Trustee"] = userTrustee;

                    ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath("Win32_SecurityDescriptor"), null);
                    userSecurityDescriptor["ControlFlags"] = 4; //SE_DACL_PRESENT
                    userSecurityDescriptor["DACL"] = new object[] { userACE };
                    //can declare share either way, where "ShareName" is the name used to share the folder
                    //ManagementPath path = new ManagementPath("Win32_Share.Name='" + ShareName + "'");
                    //ManagementObject share = new ManagementObject(path);
                    ManagementObject share = new ManagementObject(managementClass.Path + ".Name='" + ShareName + "'");

                    share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, Description, userSecurityDescriptor });

                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error sharing folders. Please make sure you install as Administrator. ERROR: " + ex.Message, "Error!");
                }
            }
            /*
             * this method is called as soon the app is started.
             * this method gets the current directory of the application,
             * calls another method which creates and shares the apps and logs folders
             * under the current directory.
             */
            private static void Share()
            {
                string strfol;
                string folder;
                string newFolder;
                DirectoryInfo di;
                try
                {
                    strfol = Application.ExecutablePath;
                    strfol = strfol.Substring(0,strfol.IndexOf(Application.ProductName + ".EXE"));
                    newFolder = "apps";
                    folder = strfol + newFolder;
                    if (!Directory.Exists(folder))
                        Directory.CreateDirectory(folder);
                    di = new DirectoryInfo(folder);
                    DirectorySecurity dSecurity = di.GetAccessControl();
                    dSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
                    di.SetAccessControl(dSecurity);
                    if (di != null)
                        QshareFolder(folder, newFolder, "");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error sharing folders. Please make sure you install as Administrator. ERROR: " + ex.Message, "Error!");
                }

            }


    Ken

    Tuesday, April 10, 2012 7:37 PM