Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating share programmatically fails with error 9

Tags:

c#

share

wmi

ObjectGetOptions options = new ObjectGetOptions();
 ManagementPath p = new ManagementPath("\\\\server01\\root" + "\\cimv2:Win32_Share");

// Make a connection to a remote computer.
ManagementScope scope = new ManagementScope("\\\\server01\\root\\cimv2");
scope.Connect();


// Create a ManagementClass object
ManagementClass managementClass = new ManagementClass(scope, p, options);
// Create ManagementBaseObjects for in and out parameters
ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");
ManagementBaseObject outParams;
// Set the input parameters
//inParams["Description"] = String.Empty;
inParams["Name"] = "test";
inParams["Path"] = @folderPath;
inParams["Type"] = 0x0; // Disk Drive
// Invoke the method on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
      throw new Exception("Unable to share directory.  Error code: " + outParams.Properties["ReturnValue"].Value);
}
}
catch (Exception e)
{
    MessageBox.Show(e.Message.ToString());
}
}

I am using the following code to set up a share, but I am always getting a return value of 9 which means invalid name. I am passing a string and have tried to use an explicit string and I still get error 9.

I am creating the share remotely rather than on local machine however. I have tried to make sure I am connecting to the remote WMI provider, but I am not sure if I have been successful.

Any suggestions from WMI gurus and others is greatly appreciated.

like image 754
Christopher Avatar asked Apr 05 '10 15:04

Christopher


2 Answers

Found the answer on another site. The folder path needs to be the local path to the machine the share is created on, not a UNC path like I was using.

like image 78
Christopher Avatar answered Nov 17 '22 04:11

Christopher


I had the same error. In my case though the problem was a trailing backslash. Doing directoryPath.TrimEnd('\') solved the problem.

like image 36
ctusch Avatar answered Nov 17 '22 03:11

ctusch