473,609 Members | 1,871 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to get users from shared folder in c#

3 New Member
Hello,

You can use this code to get list of users from shared folder of source path and also add users to destination path. It will also make destination folder shared.
It is useful to copy folder from one path to another with all its permissions.

Expand|Select|Wrap|Line Numbers
  1.   public void SetPermissions(string srcPath, string destPath)
  2.         {
  3.  
  4.             string unc;
  5.             string sharedName = string.Empty;
  6.             if (TryGetLocalFromUncDirectory(srcPath, out unc, out sharedName))
  7.             {
  8.                 sharedName = Path.GetFileName(unc);
  9.  
  10.                 if (!Directory.Exists(destPath))
  11.                 {
  12.                     Directory.CreateDirectory(destPath);
  13.                 }          
  14.  
  15.                 string userName = Environment.UserName;
  16.                 string domainName = Environment.UserDomainName;
  17.  
  18.                 AddPermissions(sharedName, domainName, userName, destPath);
  19.  
  20.             }
  21.         }
  22.  
  23.         /// <summary>
  24.         /// Remove the share.
  25.         /// </summary>
  26.  
  27.         private uint RemoveShare(string shareName)
  28.         {
  29.             try
  30.             {
  31.                 using (ManagementObject o = new ManagementObject("root\\cimv2",
  32.                 "Win32_Share.Name='" + shareName + "'", null))
  33.                 {
  34.                     ManagementBaseObject outParams = o.InvokeMethod("delete", null, null);
  35.                     return (uint)(outParams.Properties["ReturnValue"].Value);
  36.                 }
  37.             }
  38.             catch (Exception ex)
  39.             {
  40.                 return 1;
  41.             }
  42.         }
  43.  
  44.          /// <summary>
  45.         /// Creates the share.
  46.         /// </summary>
  47.  
  48.         private void AddPermissions(string sharedFolderName, string domain, string userName, string destPath)
  49.         {    
  50.  
  51.             // Step 1 - Getting the user Account Object
  52.             ManagementObject sharedFolder = GetSharedFolderObject(sharedFolderName);
  53.             if (sharedFolder==null)
  54.             {
  55.             System.Diagnostics.Trace.WriteLine("The shared folder with given name does not exist");
  56.             return;
  57.             }
  58.  
  59.             ManagementBaseObject securityDescriptorObject = sharedFolder.InvokeMethod("GetSecurityDescriptor", null, null);
  60.             if (securityDescriptorObject == null)
  61.             {
  62.             System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor of the shared path {0}.", sharedFolderName));
  63.             return;
  64.             }
  65.             int returnCode = Convert.ToInt32(securityDescriptorObject.Properties["ReturnValue"].Value);
  66.             if (returnCode != 0)
  67.             {
  68.             System.Diagnostics.Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Error extracting security descriptor of the shared path {0}. Error Code{1}.", sharedFolderName, returnCode.ToString()));
  69.             return;
  70.             }
  71.  
  72.             ManagementBaseObject securityDescriptor = securityDescriptorObject.Properties["Descriptor"].Value as ManagementBaseObject;
  73.  
  74.             // Step 2 -- Extract Access Control List from the security descriptor
  75.             int existingAcessControlEntriesCount = 0;
  76.             ManagementBaseObject[] accessControlList = securityDescriptor.Properties["DACL"].Value as ManagementBaseObject[];
  77.  
  78.             if (accessControlList == null)
  79.             {
  80.             // If there aren't any entries in access control list or the list is empty - create one
  81.             accessControlList = new ManagementBaseObject[1];
  82.             }
  83.             else
  84.             {
  85.             // Otherwise, resize the list to allow for all new users.
  86.             existingAcessControlEntriesCount = accessControlList.Length;
  87.             Array.Resize(ref accessControlList, accessControlList.Length + 1);
  88.             }
  89.  
  90.  
  91.             // Step 3 - Getting the user Account Object
  92.             ManagementObject userAccountObject = GetUserAccountObject(domain, userName);
  93.             ManagementObject securityIdentfierObject = new ManagementObject(string.Format("Win32_SID.SID='{0}'", (string)userAccountObject.Properties["SID"].Value));
  94.             securityIdentfierObject.Get();
  95.  
  96.             // Step 4 - Create Trustee Object
  97.             ManagementObject trusteeObject = CreateTrustee(domain, userName, securityIdentfierObject);
  98.  
  99.             // Step 5 - Create Access Control Entry
  100.             ManagementObject accessControlEntry = CreateAccessControlEntry(trusteeObject, false);
  101.  
  102.             // Step 6 - Add Access Control Entry to the Access Control List
  103.             accessControlList[existingAcessControlEntriesCount] = accessControlEntry;
  104.  
  105.             // Step 7 - Assign access Control list to security desciptor
  106.             securityDescriptor.Properties["DACL"].Value = accessControlList;
  107.  
  108.             // Step 8 - Assign access Control list to security desciptor
  109.             ManagementBaseObject parameterForSetSecurityDescriptor = sharedFolder.GetMethodParameters("SetSecurityDescriptor");
  110.             parameterForSetSecurityDescriptor["Descriptor"] = securityDescriptor;
  111.             sharedFolder.InvokeMethod("SetSecurityDescriptor", parameterForSetSecurityDescriptor, null);
  112.  
  113.             // Step 9 - Remove Shared Folder
  114.             RemoveShare(sharedFolderName);
  115.  
  116.             // Step 10 - Create Shared Folder
  117.             CreateSharedFolderWithUserPermissions(securityDescriptor, sharedFolderName, destPath);
  118.  
  119.  
  120.         }
  121.  
  122.         /// <summary>
  123.         /// Gets the UNC path for a local path passed to it.  empty string if folder isn't shared
  124.         ///
  125.         /// </summary>
  126.         /// <param name="local">The local path</param>
  127.         /// <param name="unc">The UNC path</param>
  128.         /// <returns>True if UNC is valid, false otherwise</returns>
  129.         /// 
  130.  
  131.         private bool TryGetLocalFromUncDirectory(string local, out string unc, out string sharedName)
  132.         {
  133.             unc = string.Empty;
  134.             sharedName = string.Empty;
  135.  
  136.             if (string.IsNullOrEmpty(local))
  137.             {
  138.                 throw new ArgumentNullException("local");
  139.             }
  140.  
  141.             ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Name FROM Win32_share WHERE path ='" + local.Replace("\\", "\\\\") + "'");
  142.             ManagementObjectCollection coll = searcher.Get();
  143.             if (coll.Count == 1)
  144.             {
  145.                 foreach (ManagementObject share in searcher.Get())
  146.                 {
  147.                     sharedName = share["Name"] as String;
  148.                     unc = "\\\\" + SystemInformation.ComputerName + "\\" + sharedName;                 
  149.                     return true;
  150.                 }
  151.             }
  152.  
  153.             return false;
  154.         }
  155.  
  156.         /// <summary>
  157.  
  158.         /// The method returns ManagementObject object for the shared folder with given name
  159.  
  160.         /// </summary>
  161.  
  162.         /// <param name="sharedFolderName">string containing name of shared folder</param>
  163.  
  164.         /// <returns>Object of type ManagementObject for the shared folder.</returns>
  165.  
  166.         private static ManagementObject GetSharedFolderObject(string sharedFolderName)
  167.         {
  168.             ManagementObject sharedFolderObject = null;
  169.  
  170.             //Creating a searcher object to search
  171.             ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from Win32_LogicalShareSecuritySetting where Name = '" + sharedFolderName + "'");
  172.             ManagementObjectCollection resultOfSearch = searcher.Get();
  173.             if (resultOfSearch.Count > 0)
  174.             {
  175.             //The search might return a number of objects with same shared name. I assume there is just going to be one
  176.             foreach (ManagementObject sharedFolder in resultOfSearch)
  177.             {
  178.             sharedFolderObject = sharedFolder;
  179.             break;
  180.             }
  181.             }
  182.             return sharedFolderObject;
  183.         }
  184.  
  185.         /// <summary>
  186.  
  187.         /// The method returns ManagementObject object for the user folder with given name
  188.  
  189.         /// </summary>
  190.  
  191.         /// <param name="domain">string containing domain name of user </param>
  192.  
  193.         /// <param name="alias">string containing the user's network name </param>
  194.  
  195.         /// <returns>Object of type ManagementObject for the user folder.</returns>
  196.  
  197.         private static ManagementObject GetUserAccountObject(string domain, string alias)
  198.         {
  199.             ManagementObject userAccountObject = null;
  200.             ManagementObjectSearcher searcher = new ManagementObjectSearcher(string.Format("select * from Win32_Account where Name = '{0}' and Domain='{1}'", alias, domain));
  201.             ManagementObjectCollection resultOfSearch = searcher.Get();
  202.             if (resultOfSearch.Count > 0)
  203.             {
  204.             foreach (ManagementObject userAccount in resultOfSearch)
  205.             {
  206.             userAccountObject = userAccount;
  207.             break;
  208.             }
  209.             }
  210.             return userAccountObject;
  211.         }
  212.  
  213.         /// <summary>
  214.  
  215.         /// Returns the Security Identifier Sid of the given user
  216.  
  217.         /// </summary>
  218.  
  219.         /// <param name="userAccountObject">The user object who's Sid needs to be returned</param>
  220.  
  221.         /// <returns></returns>
  222.  
  223.         private static ManagementObject GetAccountSecurityIdentifier(ManagementBaseObject userAccountObject)
  224.         {
  225.             ManagementObject securityIdentfierObject = new ManagementObject(string.Format("Win32_SID.SID='{0}'", (string)userAccountObject.Properties["SID"].Value));
  226.             securityIdentfierObject.Get();
  227.             return securityIdentfierObject;
  228.         }
  229.  
  230.         /// <summary>
  231.  
  232.         /// Create a trustee object for the given user
  233.  
  234.         /// </summary>
  235.  
  236.         /// <param name="domain">name of domain</param>
  237.  
  238.         /// <param name="userName">the network name of the user</param>
  239.  
  240.         /// <param name="securityIdentifierOfUser">Object containing User'sid</param>
  241.  
  242.         /// <returns></returns>
  243.  
  244.         private static ManagementObject CreateTrustee(string domain, string userName, ManagementObject securityIdentifierOfUser)
  245.         {
  246.             ManagementObject trusteeObject = new ManagementClass("Win32_Trustee").CreateInstance();
  247.             trusteeObject.Properties["Domain"].Value = domain;
  248.             trusteeObject.Properties["Name"].Value = userName;
  249.             trusteeObject.Properties["SID"].Value = securityIdentifierOfUser.Properties["BinaryRepresentation"].Value;
  250.             trusteeObject.Properties["SidLength"].Value = securityIdentifierOfUser.Properties["SidLength"].Value;
  251.             trusteeObject.Properties["SIDString"].Value = securityIdentifierOfUser.Properties["SID"].Value;
  252.             return trusteeObject;
  253.         }
  254.  
  255.  
  256.         /// <summary>
  257.  
  258.         /// Create an Access Control Entry object for the given user
  259.  
  260.         /// </summary>
  261.  
  262.         /// <param name="trustee">The user's trustee object</param>
  263.  
  264.         /// <param name="deny">boolean to say if user permissions should be assigned or denied</param>
  265.  
  266.         /// <returns></returns>
  267.  
  268.         private static ManagementObject CreateAccessControlEntry(ManagementObject trustee, bool deny)
  269.         {
  270.             ManagementObject aceObject = new ManagementClass("Win32_ACE").CreateInstance();
  271.  
  272.             aceObject.Properties["AccessMask"].Value = 0x1U | 0x2U | 0x4U | 0x8U | 0x10U | 0x20U | 0x40U | 0x80U | 0x100U | 0x10000U | 0x20000U | 0x40000U | 0x80000U | 0x100000U; // all permissions
  273.             aceObject.Properties["AceFlags"].Value = 0x0U; // no flags
  274.             aceObject.Properties["AceType"].Value = deny ? 1U : 0U; // 0 = allow, 1 = deny
  275.             aceObject.Properties["Trustee"].Value = trustee;
  276.             return aceObject;
  277.         }
  278.  
  279.         /// <summary>
  280.         /// Creates the shared folder with all user permissions.
  281.         /// </summary>
  282.  
  283.         private void CreateSharedFolderWithUserPermissions(ManagementBaseObject securityDescriptor, string sharedFolderName, string destPath)
  284.         {
  285.             // Create a ManagementClass object
  286.             ManagementClass managementClass = new ManagementClass("Win32_Share");
  287.  
  288.             // Create ManagementBaseObjects for in and out parameters
  289.             ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
  290.             ManagementBaseObject outParams;
  291.  
  292.             // Set the input parameters
  293.             inParams["Description"] = "My Files Share";
  294.             inParams["Name"] = sharedFolderName;
  295.             inParams["Path"] = destPath;
  296.             inParams["Type"] = 0x0; // Disk Drive
  297.             inParams["Access"] = securityDescriptor;
  298.  
  299.             // Invoke the method on the ManagementClass object
  300.             outParams = managementClass.InvokeMethod("Create", inParams, null);
  301.             // Check to see if the method invocation was successful
  302.             if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
  303.             {
  304.                 throw new Exception("Unable to share directory.");
  305.             }
  306.         }
Jun 2 '10 #1
0 16320

Sign in to post your reply or Sign up for a free account.

Similar topics

1
2407
by: Hubert Wong | last post by:
Hi, I am writing some C# code that moves files from a source folder to a target folder on the same machine. However, if the target folder is a shared folder, using the File.MoveTo method alone does not cause the files to be shared as well. How can I make the moved files inherit the parent folder's shared setting? I have looked into the System.Security.Permissions.FileIOPermission class but it doesn't seem to do what I'm looking for. I'm...
3
3199
by: Michael | last post by:
Hi everyone :) I have a split database with the backend on a shared folder which users access through the LAN. The front end sits on their hard drives. Apparently windows 2000 has a limit of 10 connections to shared drives. When mapping the drives I can only get 7 people out of the 9 I require before I start getting messages telling me the connection limit has been reached. I am told this is because windows counts
2
1872
by: Mr. Smith | last post by:
As the subject suggests, If I have a file path; C:\My documents\UMS\Cat1\File.txt and UMS is a shared folder shared as 'UMSPictures', is there any way I can test if each folder in the string is shared and if so return what the share name is?
6
14842
by: Jeff | last post by:
Hi - I understand how to create a directory folder, but how can I programatically create a _shared_ directory folder and set its permissions?? (I'm using VB.NET.) Thanks for your help. - Jeff
0
2486
by: digitalshehan | last post by:
Hi All, I need to find out who are the users connected to a shared folder on my machine at any given time. Its something like what you can find in the Computer Management console (control panel -> Administrative tools -> computer management) I've read something about WMI and NetShareEnum, but I'm not too sure if it can do what I want.
6
3927
by: jzdeng | last post by:
Hi, All I use VS 2005 to create a web service. The web service is used to create a sheared folder. It works fine we I run it from VS 2005. But, when I move it to inetpub, it does not work (folder is created but is not shared). Does anyone know how to solve this problem? Thanks.
7
4032
by: Ibrahim. | last post by:
Hello, How can I access a Shared Folder of the Server by using the following control. 1. I need to download files from c:\resumes folde by using the following; <asp:HyperLink NavigateUrl='<%#DataBinder.Eval(Container.DataItem,"FilePath") %>' a. FilePath is a database field holding the value "c:\resumes\myresume.doc"
0
1144
by: ajl | last post by:
I need to list all users who have opened a file in a shared folder.
1
15033
by: JordanRieger | last post by:
Here is a nasty issue that has been giving me grief for the last couple days. This requires good knowledge of IIS, MSXML, and Windows/NTFS permissions. We have an existing ASP (VBScript) app hosted on IIS 6.0 (W2K3). We need to restrict access to specific users within our company network. To reduce development effort I figured the easiest solution was to enable Integrated Windows Authentication. However once I enable IWA and disable...
1
6625
by: abhimusale | last post by:
I am developing application in c#. I added users (except administrator and everyone) and assign permissions to them in shared folder. I want to get list of all users and their permissions to whom file sharing is allowed. I tried to get this using Win32 class and system.management. Also searched on google but not get any specific link. Plz help me. Thanks in advance Abhijeet
0
8573
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8406
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7002
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5510
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4021
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4085
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1672
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1389
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.