Click here to Skip to main content
15,879,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to create a folder and make the folder shared to everyone and give permission to everyone.

I have tried this for sharing and its not working (the folder is not share when i checked the properties)

How-to-Share-Windows-Folders-Using-C [^]

For folder permission i have tried this,


C#
private static void SetPermissions(string dirPath)
      {
          DirectoryInfo info = new DirectoryInfo(dirPath);
          WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();
          DirectorySecurity ds = info.GetAccessControl();
          ds.AddAccessRule(new FileSystemAccessRule(self.Name,
          FileSystemRights.FullControl,
          InheritanceFlags.ObjectInherit |
          InheritanceFlags.ContainerInherit,
          PropagationFlags.None,
          AccessControlType.Allow));
          info.SetAccessControl(ds);
      }



Please Assist with some different approach if this is not correct.

Thanks in Advance
Posted
Updated 3-May-23 2:40am
v2

You set the ACL on the folder, but you do not configure a share on it.

Moreover, configuring access lists with individual accounts is an administrator's nightmare. Better create a group with appropriate permissions, and add the user to the group. You then just have to set the ACL for the group, not the individual. If someone is leaving and his permissions have to be thrown away, you just have to remove the user from the group.

I do not know how to create a share from C#, apart from executing a plain old net share command:
net share [share_name]=[path]

You can get more informations on net share command by typing net share /? in a console.
 
Share this answer
 
v2
Run this as Administrator. Add manifest file to your project.

ShareFolder Method creates the directory and share's it but share permission are Read Only. To change this permission we will call method SetPermission.

Add Reference to System.Management.dll

C#
using System;
using System.Management;
using System.IO;
public string ShareFolder(string FolderPath, string ShareName, string Description)
        {
            string strSharePath = FolderPath;
            string strShareName = ShareName;
            string strShareDesc = Description;
            string msg = string.Empty;
            try
            {
                Directory.CreateDirectory(strSharePath);
                ManagementClass oManagementClass = new ManagementClass("Win32_Share");
                ManagementBaseObject inputParameters = oManagementClass.GetMethodParameters("Create");
                ManagementBaseObject outputParameters;
                inputParameters["Description"] = strShareDesc;
                inputParameters["Name"] = strShareName;
                inputParameters["Path"] = strSharePath;
                inputParameters["Type"] = 0x0;//disk drive 
                inputParameters["MaximumAllowed"] = null;
                inputParameters["Access"] = null;

                inputParameters["Password"] = null;


                outputParameters = oManagementClass.InvokeMethod("Create", inputParameters, null);

                if ((uint)(outputParameters.Properties["ReturnValue"].Value) != 0)
                {
                    msg = "There is a problem while sharing the directory.";
                    throw new Exception("There is a problem while sharing the directory.");
                }
                else
                {
                    msg = ("Share Folder has been created with the name :" + strShareName);
                }


            }
            catch (Exception ex)
            {
                msg = (ex.Message.ToString());
            }
            return msg;
        }


This method will set permission.

Get System Domain.
C#
string Domain = Environment.UserDomainName;

In AddPermission Method pass sharedFolderName same as shareName set by you in previous method or the share name of directory for which you want to change permission. In userName field use name of account for which you want to set/change permission. Example - Everyone, Administrators etc.
C#
using System;
using System.Management;
using System.Globalization;
 public void AddPermissions(string sharedFolderName, string domain, string userName)
        {

            // Step 1 - Getting the user Account Object
            ManagementObject sharedFolder = GetSharedFolderObject(sharedFolderName);
            if (sharedFolder == null)
            {
                System.Diagnostics.Trace.WriteLine("The shared folder with given name does not exist");
                return;
            }

            ManagementBaseObject securityDescriptorObject = sharedFolder.InvokeMethod("GetSecurityDescriptor", null, null);
            if (securityDescriptorObject == null)
            {
                System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor of the shared path {0}.", sharedFolderName));
                return;
            }
            int returnCode = Convert.ToInt32(securityDescriptorObject.Properties["ReturnValue"].Value);
            if (returnCode != 0)
            {
                System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor of the shared path {0}. Error Code{1}.", sharedFolderName, returnCode.ToString()));
                return;
            }

            ManagementBaseObject securityDescriptor = securityDescriptorObject.Properties["Descriptor"].Value as ManagementBaseObject;

            // Step 2 -- Extract Access Control List from the security descriptor
            int existingAcessControlEntriesCount = 0;
            ManagementBaseObject[] accessControlList = securityDescriptor.Properties["DACL"].Value as ManagementBaseObject[];

            if (accessControlList == null)
            {
                // If there aren't any entries in access control list or the list is empty - create one
                accessControlList = new ManagementBaseObject[1];
            }
            else
            {
                // Otherwise, resize the list to allow for all new users.
                existingAcessControlEntriesCount = accessControlList.Length;
                Array.Resize(ref accessControlList, accessControlList.Length + 1);
            }


            // Step 3 - Getting the user Account Object
            ManagementObject userAccountObject = GetUserAccountObject(domain, userName);
            ManagementObject securityIdentfierObject = new ManagementObject(string.Format("Win32_SID.SID='{0}'", (string)userAccountObject.Properties["SID"].Value));
            securityIdentfierObject.Get();

            // Step 4 - Create Trustee Object
            ManagementObject trusteeObject = CreateTrustee(domain, userName, securityIdentfierObject);

            // Step 5 - Create Access Control Entry
            ManagementObject accessControlEntry = CreateAccessControlEntry(trusteeObject, false);

            // Step 6 - Add Access Control Entry to the Access Control List
            accessControlList[existingAcessControlEntriesCount] = accessControlEntry;

            // Step 7 - Assign access Control list to security desciptor 
            securityDescriptor.Properties["DACL"].Value = accessControlList;

            // Step 8 - Assign access Control list to security desciptor 
            ManagementBaseObject parameterForSetSecurityDescriptor = sharedFolder.GetMethodParameters("SetSecurityDescriptor");
            parameterForSetSecurityDescriptor["Descriptor"] = securityDescriptor;
            sharedFolder.InvokeMethod("SetSecurityDescriptor", parameterForSetSecurityDescriptor, null);
        }

        /// <summary>
        /// The method returns ManagementObject object for the shared folder with given name
        /// </summary>
        /// <param name="sharedFolderName">string containing name of shared folder</param>
        /// <returns>Object of type ManagementObject for the shared folder.</returns>

        private static ManagementObject GetSharedFolderObject(string sharedFolderName)
        {
            ManagementObject sharedFolderObject = null;

            //Creating a searcher object to search 
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_LogicalShareSecuritySetting where Name = '" + sharedFolderName + "'");
            ManagementObjectCollection resultOfSearch = searcher.Get();
            if (resultOfSearch.Count > 0)
            {
                //The search might return a number of objects with same shared name. I assume there is just going to be one
                foreach (ManagementObject sharedFolder in resultOfSearch)
                {
                    sharedFolderObject = sharedFolder;
                    break;
                }
            }
            return sharedFolderObject;
        }

        /// <summary>
        /// The method returns ManagementObject object for the user folder with given name
        /// </summary>
        /// <param name="domain">string containing domain name of user </param>
        /// <param name="alias">string containing the user's network name </param>
        /// <returns>Object of type ManagementObject for the user folder.</returns>

        private static ManagementObject GetUserAccountObject(string domain, string alias)
        {
            ManagementObject userAccountObject = null;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(string.Format("select * from Win32_Account where Name = '{0}' and Domain='{1}'", alias, domain));
            ManagementObjectCollection resultOfSearch = searcher.Get();
            if (resultOfSearch.Count > 0)
            {
                foreach (ManagementObject userAccount in resultOfSearch)
                {
                    userAccountObject = userAccount;
                    break;
                }
            }
            return userAccountObject;
        }

        /// <summary>
        /// Returns the Security Identifier Sid of the given user
        /// </summary>
        /// <param name="userAccountObject">The user object who's Sid needs to be returned</param>
        /// <returns></returns>

        private static ManagementObject GetAccountSecurityIdentifier(ManagementBaseObject userAccountObject)
        {
            ManagementObject securityIdentfierObject = new ManagementObject(string.Format("Win32_SID.SID='{0}'", (string)userAccountObject.Properties["SID"].Value));
            securityIdentfierObject.Get();
            return securityIdentfierObject;
        }

        /// <summary>
        /// Create a trustee object for the given user
        /// </summary>
        /// <param name="domain">name of domain</param>
        /// <param name="userName">the network name of the user</param>
        /// <param name="securityIdentifierOfUser">Object containing User's sid</param>
        /// <returns></returns>

        private static ManagementObject CreateTrustee(string domain, string userName, ManagementObject securityIdentifierOfUser)
        {
            ManagementObject trusteeObject = new ManagementClass("Win32_Trustee").CreateInstance();
            trusteeObject.Properties["Domain"].Value = domain;
            trusteeObject.Properties["Name"].Value = userName;
            trusteeObject.Properties["SID"].Value = securityIdentifierOfUser.Properties["BinaryRepresentation"].Value;
            trusteeObject.Properties["SidLength"].Value = securityIdentifierOfUser.Properties["SidLength"].Value;
            trusteeObject.Properties["SIDString"].Value = securityIdentifierOfUser.Properties["SID"].Value;
            return trusteeObject;
        }


        /// <summary>
        /// Create an Access Control Entry object for the given user
        /// </summary>
        /// <param name="trustee">The user's trustee object</param>
        /// <param name="deny">boolean to say if user permissions should be assigned or denied</param>
        /// <returns></returns>

        private static ManagementObject CreateAccessControlEntry(ManagementObject trustee, bool deny)
        {
            ManagementObject aceObject = new ManagementClass("Win32_ACE").CreateInstance();

            aceObject.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x80000U | 0x100000U; // all permissions
            aceObject.Properties["AceFlags"].Value = 0x0U; // no flags
            aceObject.Properties["AceType"].Value = deny ? 1U : 0U; // 0 = allow, 1 = deny
            aceObject.Properties["Trustee"].Value = trustee;
            return aceObject;
        }

You can download working solution from here.
 
Share this answer
 
Comments
CHill60 28-Feb-18 8:48am    
The post was answered over 2 years ago. Posting solutions to old posts where the solution contains a link is often perceived as site-driving and can lead to your account being suspended or closed.
Stick to answering new posts where the OP still needs help
Refer: Add “Everyone” privilege to folder using C#.NET[^]

C#
DirectorySecurity sec = Directory.GetAccessControl(path);

// Using this instead of the "Everyone" string means we work on non-English systems.
SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
sec.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.Modify | FileSystemRights.Synchronize, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
Directory.SetAccessControl(path, sec);


Hope this helps!
 
Share this answer
 
private static void GrantAccess(string file)
{
bool exists = System.IO.Directory.Exists(file);
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(file);
Console.WriteLine("The Folder is created Sucessfully");
}
else
{
Console.WriteLine("The Folder already exists");
}
DirectoryInfo dInfo = new DirectoryInfo(file);
DirectorySecurity dSecurity = dInfo.GetAccessControl();
dSecurity.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.NoPropagateInherit, AccessControlType.Allow));
dInfo.SetAccessControl(dSecurity);

}
 
Share this answer
 
Comments
Richard Deeming 3-May-23 9:00am    
So essentially an exact copy of what solution 2 said eight years ago, except as an unformatted, unexplained code-dump.

Stick to answering new questions unless you have something new and interesting to add to the discussion.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900