Search code examples
c#.netwinformswinapishared-directory

Sharing Folder API


I have C# WinForm application that needs to set sharing permission to some folder, and specify what users have access read/write/delete. I was wondering if there is any api or way to call something similar to when you right click on folder select Properties/Sharing/Advanced Sharing and window opens.

Advanced Sharing Window

If you know of anyway calling this window from c# I would appreciate if you share your knowledge. I want to call this window.


Solution

  • You can do it through Win32 API:

    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
    
                // Invoke the method on the ManagementClass object
                outParams = managementClass.InvokeMethod("Create", inParams, null);
                if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
                {
                    throw new Exception("Unable to share directory.");
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "error!");
            }
        }
    

    Usage: QshareFolder("c:\TestShare", "Test Share", "This is a Test Share");

    Source: http://www.codeproject.com/Articles/18624/How-to-Share-Windows-Folders-Using-C