Notifications
Clear all

[Closed] create and share a folder with maxscript

It is because, that was just a piece of code, not full.
Here is the version of code for sharing a folder in C# for English version of Windows:

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"

We have to combine it with your code, which replaces standard word “Everyone”. I tried to do it by myself, but I get erros. Please help me till the end, please

new ManagementObject(mc.Path + ".Name='" + CondivisionName + "'");

this part i don’t understand and don’t have time to figure it out. what is CondivisionName?

Denis, I don’t really understand what is this, I found this code on a website,

    [ https://social.msdn.microsoft.com/Forums/windowsdesktop/ar-SA/de213b61-dc7e-4f33-acdb-893aa96837fa/c-set-directory-sharing-permission-full-control-for-everyone-programmatically-in-windows-7-or?forum=windowssdk ]( https://social.msdn.microsoft.com/Forums/windowsdesktop/ar-SA/de213b61-dc7e-4f33-acdb-893aa96837fa/c-set-directory-sharing-permission-full-control-for-everyone-programmatically-in-windows-7-or?forum=windowssdk) 
    
    It should allow to set up security permission.
    
    On another website it says:

      //string CondivisionName = "HRISSelRecrutRO1DEV";
    which obove was set as groupname:
string groupName = "HRISSelRecrutRO1DEV";
    Here is the full code I found with this explanation:

  string groupName = "HRISSelRecrutRO1DEV"; string computerName = "CIS1100873"; string sharedFolderName = "hristest12";
  NTAccount ntAccount = new NTAccount(groupName); 
  
  //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"] = computerName + @"\" + groupName; userTrustee["SID"] = utenteSIDArray;
  
  //ACE
  
  ManagementObject userACE = new ManagementClass(new ManagementPath("Win32_Ace"), null);
  userACE["AccessMask"] = 1179817; //Full access = 2032127 ; Change = 1245631 ; Read = 1179817
  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
  
  //string CondivisionName = "HRISSelRecrutRO1DEV";
  
  string CondivisionName = sharedFolderName;
  ManagementClass mc = new ManagementClass("Win32_Share");
  ManagementObject share = new ManagementObject(mc.Path + ".Name='" + CondivisionName + "'");
  share.InvokeMethod("SetShareInfo", new object[] { Int32.MaxValue, "", userSecurityDescriptor });
    [ http://www.developpez.net/forums/d1165619/dotnet/langages/csharp/definir-permissions-d-repertoire-partage/ ]( http://www.developpez.net/forums/d1165619/dotnet/langages/csharp/definir-permissions-d-repertoire-partage/) 

For my case, it is not strictly necessary to link it to the computer groupname. It is enough in security tab to put Everyone like in share tab

i do here everything that the article above says but it doesn’t work for me. if anyone have a time to play with be welcome:

fn CreateSecurityOpsAssembly =
(
source  = ""
source += "using System;
"
source += "using System.IO;
"
source += "using System.Security.Principal;
"
source += "using System.Security.AccessControl;
"
source += "using System.Management;
"
source += " 
"
source += "namespace SystemSecurity
"
source += "{
"
source += "    public class AccessOps
"
source += "    {
"
source += "        public bool SetFullAccessControl(String path)
"
source += "        {
"
source += "            if (!Directory.Exists(path))
"
source += "            {
"
source += "                DirectoryInfo info = Directory.CreateDirectory(path);
"
source += "                if (!info.Exists) return false;
"
source += "            }
"
source += "            DirectorySecurity sec = Directory.GetAccessControl(path);
"
source += "       
"
source += "            SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
"
source += "            sec.AddAccessRule(new FileSystemAccessRule(everyone, 
"
source += "                FileSystemRights.Modify | FileSystemRights.Synchronize, 
"
source += "                InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
"
source += "                PropagationFlags.None, AccessControlType.Allow));
"
source += "            Directory.SetAccessControl(path, sec);
"
source += "            return Directory.Exists(path);
"
source += "        }
"
source += "        public Object ShareFolderPermission(String SharedFolderPath, String ShareName = \"\", String Description = \"\")
"
source += "        {
"
source += "            if (!Directory.Exists(SharedFolderPath))
"
source += "            {
"
source += "                bool result = SetFullAccessControl(SharedFolderPath);
"
source += "                if (!result) return false;
"
source += "            }
"
source += "            if (Directory.Exists(SharedFolderPath)) try
"
source += "            {
"
source += "                // Calling Win32_Share class to create a shared folder
"
source += "                ManagementClass managementClass = new ManagementClass(\"Win32_Share\");
"
source += "                // Get the parameter for the Create Method for the folder
"
source += "                ManagementBaseObject inParams = managementClass.GetMethodParameters(\"Create\");
"
source += "                // Assigning the values to the parameters
"
source += "                inParams[\"Description\"] = Description;
"
source += "                inParams[\"Name\"] = ShareName;
"
source += "                inParams[\"Path\"] = SharedFolderPath;
"
source += "                inParams[\"Type\"] = 0x0;
"
source += "                inParams[\"MaximumAllowed\"] = null;
"
source += "                inParams[\"Password\"] = null;
"
source += "                inParams[\"Access\"] = null; // Make Everyone has full control access.
"
source += "                // Finally Invoke the Create Method to do the process
"
source += "                ManagementBaseObject outParams = managementClass.InvokeMethod(\"Create\", inParams, null);
"
source += "                // Validation done here to check sharing is done or not
"
source += "                return ((uint)(outParams.Properties[\"ReturnValue\"].Value) != 0);
"
source += "            }
"
source += "            catch (Exception e)
"
source += "            {
"
source += "                return e;
"
source += "            }
"
source += "            return true;
"
source += "        }
"
source += "        public Object GetFullControl(String SharedFolderPath = \"\", String Description = \"\")
"
source += "        {
"
source += "            //user selection
"
source += "            NTAccount ntAccount = new NTAccount(\"Everyone\");
"
source += "            //SID
"
source += "            SecurityIdentifier userSID = (SecurityIdentifier)ntAccount.Translate(typeof(SecurityIdentifier));
"
source += "            byte[] utenteSIDArray = new byte[userSID.BinaryLength];
"
source += "            userSID.GetBinaryForm(utenteSIDArray, 0);
"
source += "            //Trustee
"
source += "            ManagementObject userTrustee = new ManagementClass(new ManagementPath(\"Win32_Trustee\"), null);
"
source += "            userTrustee[\"Name\"] = \"Everyone\";
"
source += "            userTrustee[\"SID\"] = utenteSIDArray;
"
source += "            //ACE
"
source += "            ManagementObject userACE = new ManagementClass(new ManagementPath(\"Win32_Ace\"), null);
"
source += "            userACE[\"AccessMask\"] = 2032127;								 //Full access
"
source += "            userACE[\"AceFlags\"] = AceFlags.ObjectInherit | AceFlags.ContainerInherit;
"
source += "            userACE[\"AceType\"] = AceType.AccessAllowed;
"
source += "            userACE[\"Trustee\"] = userTrustee;
"
source += "            ManagementObject userSecurityDescriptor = new ManagementClass(new ManagementPath(\"Win32_SecurityDescriptor\"), null);
"
source += "            userSecurityDescriptor[\"ControlFlags\"] = 4; //SE_DACL_PRESENT 
"
source += "            userSecurityDescriptor[\"DACL\"] = new object[] { userACE };
"
source += "            //UPGRADE SECURITY PERMISSION
"
source += "            ManagementClass mc = new ManagementClass(\"Win32_Share\");
"
source += "            ManagementObject share;
"
source += "            try
"
source += "            {
"
source += "                share = new ManagementObject(mc.Path + \".Name='\" + SharedFolderPath + \"'\");
"
source += "                share.InvokeMethod(\"SetShareInfo\", new object[] { Int32.MaxValue, Description, userSecurityDescriptor });
"
source += "            }
"
source += "            catch (ManagementException e)
"
source += "            {
"
source += "                return e.ErrorCode;
"
source += "            }
"
source += "            return true;
"
source += "            //This allow me to upgrade the security permission of \"Everyone\" in Windows Vista & 7 and get \"Full Control\"
"
source += "        }
"
source += "    }
"
source += "}
"

	csharpProvider = dotnetobject "Microsoft.CSharp.CSharpCodeProvider"
	compilerParams = dotnetobject "System.CodeDom.Compiler.CompilerParameters"

	compilerParams.ReferencedAssemblies.AddRange #("system.dll", "mscorlib.dll", "system.management.dll")

	compilerParams.GenerateInMemory = on
	compilerResults = csharpProvider.CompileAssemblyFromSource compilerParams #(source)
	
	assembly = compilerResults.CompiledAssembly
	assembly.CreateInstance "SystemSecurity.AccessOps"
)
global SecurityOps = CreateSecurityOpsAssembly()

/*
SecurityOps.SetFullAccessControl @"c:	emp\sec2"
SecurityOps.ShareFolderPermission @"c:	emp\sec2" "my_folder" "Shared"
*/ 

Thank you, Denis for your efforts. I hope there are still people ready to help. I will try to play with it as well.

Denis, I will soon get crazy with this folder sharing. I’ve tried today in different ways and no luck.

Look, is it possible to send from C# the translated word “everyone”to DosCommand?

fn create_share folderPath =
(
	HiddenDosCommand ("mkdir "+folderPath)
	HiddenDosCommand ("net share " + (pathConfig.stripPathToLeaf folderPath) + "=" + "\"" + folderPath + "\"" + " /GRANT:Everyone,FULL")
)

Or may be to save it to a file and batch it in cmd somehow.

What if you use “@” to enforce a literal string?

fn create_share folderPath =
(
	HiddenDosCommand ("mkdir "+folderPath)
	HiddenDosCommand ("net share " + (pathConfig.stripPathToLeaf folderPath) + "=" + "\"" + folderPath + "\"" +@" /GRANT:Everyone,FULL")
)

Or may be to save it to a file and batch it in cmd somehow.

That might be the best approach, if you can get the functionality you need with .bat file.

1 Reply
(@try2script)
Joined: 10 months ago

Posts: 0

It still does not become shared.

But this will require to use proper Encoding when saving the translated word. (To be considered System Local Language)

Almost DONE!

Here is the final WORKING version:

(	
	fn doesFolderExistDNfn folderPath =
	(
		local sioDir = dotNetClass "System.IO.Directory"
		(SIODir.Exists folderPath)
	)
	fn create_share folderPath =
	(
		if not doesFolderExistDNfn folderPath do
			makeDir folderPath
[B]		Universal_Everyone = "Everyone"--"все" 
		LocaleCode_Page = 866[/B]
		batchCommandBuffer = #("@ECHO OFF", "net share " + (pathConfig.stripPathToLeaf folderPath) + "=" + "\"" + folderPath + "\"" + " /UNLIMITED"+" /GRANT:" + Universal_Everyone + ",FULL", "cacls " + "\"" + folderPath + "\"" + " /e /p " + Universal_Everyone + ":f")
		print (batchCommandBuffer as string)
		(dotnetclass "System.IO.File").WriteAllLines (sysInfo.tempdir +"share_folder.bat") batchCommandBuffer ((dotNetClass "System.Text.Encoding").GetEncoding(LocaleCode_Page))
		ShellLaunch (sysInfo.tempdir +"\\share_folder.bat") ""
	)
	create_share (sysInfo.tempdir + "test_folder")
)

I just need your help to get 2 variables from System Locale

  1. Universal_Everyone
  2. LocaleCode_Page (needed for correct encoding)

We have computers with different Locale Languages in our Company, I just need to make these variables work everywere.

You will see a table with Code Page under REMARKS here:

https://msdn.microsoft.com/library/system.text.encoding%28v=vs.110%29.aspx

I have found this on a website:


     $everyone = New-Object System.Security.Principal.SecurityIdentifier([System.Security.Principal.WellKnownSidType]::WorldSid, $null); 
    
       
   So, is it possible to get by DOTNET?
   
   I started, but I don't know how to continue:
(dotNetClass "System.Security.Principal.SecurityIdentifier")
 (dotNetClass "System.Security.Principal.WellKnownSidType").WorldSid
 (dotNetClass "System.Security.Principal.WellKnownSidType").NullSid
   

I have found the codepage

in cmd type chcp and you get
Active code page:…

but how to get the result in 3d max from cmd?

(
       hiddendosCommand ("chcp") exitcode:&exitcode
       print exitcode
   )    

this gives 0 which means success, but no the result

–================================================
((dotNetClass “System.Console”).OutputEncoding).CodePage – does not give proper codepage

Page 2 / 3