Sie sind auf Seite 1von 9

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

Hi, I want to set Directory sharing permission by c# code. I try to use this code: 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); This code works fine in Windows xp but don't work in Windows Vista or 7. In Windows 7, after executing the code, Everyone have only the Read permission. How can I set Full control for Everyone in Windows 7? I found this link but it don't help me. http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/cfe4dea3-5f08-431f-9d2e-145f36b268bb http://social.msdn.microsoft.com/Forums/en-US/vblanguage/thread/63e8fd64-3567-4dd1-9950-231a28ca19c6 http://cjwdev.wordpress.com/2010/05/27/shared-a-folder-and-setting-share-permissions-from-vb-net/

- Andrea Bianchi - site: http://www.BianchiAndrea.com

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

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

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

Can't set FullControl on directory


I'm trying to set FullControl for Everyone programmatically on a Windows 7 box with no luck. var dirSec = dir.GetAccessControl(); var fsar = new FileSystemAccessRule( "Everyone", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); dirSec.AddAccessRule(fsar); dir.SetAccessControl(dirSec);

This adds some permissions for the Everyone group (List and Read), but not full control. If I edit the security permissions using Explorer I can set it to FullControl. Any ideas why it's failing? There are no error messages from my attempts. This should work fine: string path = @"C:\test"; DirectorySecurity ds = Directory.GetAccessControl(path); ds.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow)); Directory.SetAccessControl(path, ds); If that does not work then it seems that your application does not have rights to give that kind access rule. Try to implement impersonation. Here is a sample: WindowsIdentity Impersonation using C# Code
link|improve this answer

foreach (FileSystemRights permission in Enum.GetValues(typeof(FileSystemRights))) { myDirectorySecurity.AddAccessRule( new FileSystemAccessRule(user, permission, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit | InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)); }
link|improve this answer

WindowsIdentity Impersonation using C# Code


RATE THIS

itsmeskv 28 May 2008 11:18 PM

19
using System; using System.Collections.Generic; using System.Text; using System.Security.Principal; using System.Runtime.InteropServices; using System.Security.Permissions; namespace Test { public class ImpersonateUser { [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser( String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); private static IntPtr tokenHandle = new IntPtr(0); private static WindowsImpersonationContext impersonatedUser; // If you incorporate this code into a DLL, be sure to demand that it // runs with FullTrust. [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public void Impersonate(string domainName, string userName, string password) { //try {

// Use the unmanaged LogonUser function to get the user token for // the specified user, domain, and password. const int LOGON32_PROVIDER_DEFAULT = 0; // Passing this parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // ---- Step - 1 // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser( userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); // tokenHandle - new security token if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); } // ---- Step - 2 WindowsIdentity newId = new WindowsIdentity(tokenHandle); // ---- Step - 3 impersonatedUser = newId.Impersonate(); } } // Stops impersonation public void Undo() { impersonatedUser.Undo(); // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle); } } }

how to use it ImpersonateUser iu = new ImpersonateUser(); iu.Impersonate("domain", "userName", "password"); //your code iu.Undo();

How to set full control to a directory


I am using the following code to set full control DirectorySecurity myDirectorySecurity = source.GetAccessControl(); string User = "Srinivass\\Admin"; myDirectorySecurity.AddAccessRule(new FileSystemAccessRule( User, FileSystemRights.Modify, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow) ); source.SetAccessControl(myDirectorySecurity); But it is giving special permissions to this folder only. I want to give full controll permissions to all subfolders. Please anyone can help me.

If you want full control then you should pass FileSystemRights.FullControl rather thanFileSystemRights.Modify. You also need to pass both ContainerInherit and ObjectInherit for the InheritanceFlags.ObjectInherit only applies the ACE for leaf objects (e.g. files), but you presumably want to apply it to containers (e.g. folders) too. So you should use: new FileSystemAccessRule( User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow

)
link|improve this answer

Try changing PropagationFlags parameter to PropagationFlags.None. Your access rule should look like: new FileSystemAccessRule( User, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow ); Then, check the Security tab in Windows Explorer, and you should see the folder (and any newly created objects going forward) having Full Control.
link|improve this answer

dar permisos de usuario a una carpeta


Asked By Gustavo Cantero 27-Feb-09 11:22 AM

Deberas hacer algo como esto: using System.IO; using System.Security.AccessControl; using System.Security.Principal; ... FileSecurity objFileSec = File.GetAccessControl("c:\path"); objFileSec.AddAccessRule(new FileSystemAccessRule(new NTAccount("usuario"), FileSystemRights.Modify, AccessControlType.Allow)); File.SetAccessControl("c:\path", objFileSec); Espero te sirva. Saludos.