Search code examples
c#.netwindows-server

How to share remote folders?


I'm working on a .NET class that will be used in tools to manage our Active Directory accounts. Each of our accounts gets a network home directory, which can be located on a couple different servers, depending on what type of account we're working with.

I can create and delete the folders just fine, but I'm running into trouble sharing the folders. I found some code here that seems to be what I want, but it isn't working properly for me. The return value I get is 2, but I'm not sure what that indicates.

This shouldn't be a file permission issue, since I'm running my test application as myself, and I have full control of the folder that I'm trying to share (and each of its parent folders).

Here's my (modified) version of the code:

char[] delim = { '\\' };
// folderPath is a string (UNC path)
string[] drivePath = folderPath.Split(delim); 

// 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"] = "";
inParams["Name"] = drivePath[3];
inParams["Path"] = folderPath;
inParams["Type"] = 0x0; // Disk Drive

// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);

I've tried outputting the other outParams, but it looks like ReturnValue is all I get.

Is there a different way to share a remote folder that would work better?


Solution

  • I'll answer myself, in case someone else finds this later.

    I ended up going with the extremely unsexy answer of using PSExec and NET SHARE:

    // Retrieve drive path from AD
    char[] delim = { '\\' };
    string[] drivePath = userAD.HomeDirectory.Split(delim);
    
    // Configure startup properties of process
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.FileName = "C:\\Windows\\System32\\psexec.exe";
    
    // Build arguments for folder on alpha or student
    startInfo.Arguments = "\\\\" + serverName + " -s net share " + shareName + "=" folderPath + "$ /GRANT:\"authenticated users\",full";
    
    Process process = new Process();
    
    process.StartInfo = startInfo;
    process.Start();
    process.WaitForExit();
    

    Note that in our environment the program will already be running under a user who has Full Control permissions on the folder being shared. To allow similar for a non-privileged user, you have to specify a name and password in startInfo.Arguments.