Listing shares on a Computer with C#

I was trying to search for info on how to do this and came up with this . It uses a couple of classes .

First off we need to use the namespace to retrieve these classes . So if your building a project make sure you add this namespace and also have a using statement .


The classes that are used are :




Management Scope


Here is the whole piece of code :

  //New instance of the management path so we can use its properties
  ManagementPath path = new ManagementPath();

//Set the Servername
  path.Server = ServerName;

//Set the WMI namespace
  path.NamespacePath = @"root\cimv2";

//Here we are using the default connections but we can also use different.
  //Username and password if we need to.
  ConnectionOptions oConn = new ConnectionOptions();

//Set the Scope ...Computername and WMI namespace
  ManagementScope scope = new ManagementScope(path, oConn);

//Set the WMI Class
  path.RelativePath = "Win32_Share";

//Set shares to null
  ManagementClass Shares = null;

//Here we are connecting using the Servername and WMI Namespace/Class
  using (Shares = new ManagementClass(scope, path, null))
  //Return a collection of Shares here
  ManagementObjectCollection moc = Shares.GetInstances();

//Go thru each share and display its name property in the list box.
  foreach (ManagementObject mo in moc)

catch (Exception) //catch any exceptions we might have .
  MessageBox.Show("Unable to return sharenames . Please make share Servername is correct.");

I will explain more in a later Blog . Busy Day . This basically will return all shares (even Hidden Shares ) of a computer/Server. You can see that I'm putting the result in a listbox called lstShares.