Thursday, July 17, 2008

C# Sharing / UN-sharing Local Disk Folder

Following code snippet share and removes the share on local disk folder.

using System.Management;
using System.IO;

namespace FolderNetworkSharing
{
public class FolderSharer
{
public void ShareFolder(string folderPath, string shareName)
{
// 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"] = "My Files Share";
inParams["Name"] = shareName;
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.") }
}

public void RemoveShare(string shareName)
{

// Create ManagementBaseObjects for in and out parameters
ManagementObject mObject = new ManagementObject("root\\cimv2", "Win32_Share.Name='" + shareName + "'", null);
ManagementBaseObject outParams;

// Invoke the method on the ManagementClass object
outParams = mObject.InvokeMethod("delete", null, null);

// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
throw new Exception("Unable to remove share.");
}

}
}
}

0 comments: