Thursday, September 11, 2008

[.NET] How to create a shared folder in C#

To cut a not so long story even shorter, this can be done with the following snippet: 

using System.IO;
using System.Management;


//First create your directory
DirectoryInfo myDir = new DirectoryInfo(@"C:\shared");


// Create an instance of ManagementClass
ManagementClass managementClass = new ManagementClass("Win32_Share");
// ManagementBaseObjects reference for in and out parameters
ManagementBaseObject inParams;
ManagementBaseObject outParams;
inParams = managementClass.GetMethodParameters("Create");
// Set input parameters
inParams["Description"] = "Shared directory";
inParams["Name"] = "shared";//this needs to match with folder name!
inParams["Path"] = @"C:\shared";
inParams["Type"] = 0x0; // Disk Drive
// InvokeMethod call on the ManagementClass object
outParams = managementClass.InvokeMethod("Create", inParams, null);
// Check outcome
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
   //Unable to share directory

The above solution is quite sweet and seems to work perfectly - for further details see the article where I originally found the snippet to share the directory:

Man - do I suck!?!

kick it on

No comments: