确定是否在.NET中共享文件夹

时间:2020-03-06 14:45:14  来源:igfitidea点击:

是否可以通过.net框架确定文件夹是否共享?

Diretory,DirectoryInfo或者FileAttributes似乎都没有任何对应的字段。

我忘记提及的一件事是我想检查网络共享。但是我将研究WMI的东西。

解决方案

尝试使用WMI并执行" SELECT * FROM Win32_ShareToDirectory"查询。

我们可以使用WMI Win32_Share。
看一眼:

http://www.gamedev.net/community/forums/topic.asp?topic_id=408923

显示用于查询,创建和删除共享文件夹的示例。

我们可以使用WMI Win32_Share获取所有共享文件夹的列表,并查看我们要查找的文件夹是否在它们之间。这是一个片段,可能会:

public static List<string> GetSharedFolders()
{

  List<string> sharedFolders = new List<string>();

  // Object to query the WMI Win32_Share API for shared files...

  ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");

  ManagementBaseObject outParams;

  ManagementClass mc = new ManagementClass("Win32_Share"); //for local shares

  foreach (ManagementObject share in searcher.Get()){

  string type = share["Type"].ToString();

  if (type == "0") // 0 = DiskDrive (1 = Print Queue, 2 = Device, 3 = IPH)
  {
    string name = share["Name"].ToString(); //getting share name

    string path = share["Path"].ToString(); //getting share path

    string caption = share["Caption"].ToString(); //getting share description

    sharedFolders.Add(path);
  }

  }

  return sharedFolders;

}

请注意,我从该链接上以字节为单位进行了残酷的复制粘贴

为这只猫换皮的另一种方法是使用powershell(如果已安装)调用wmi调用,包括对System.Management.Automation的引用,大多数情况下,它将位于\ program files \ referenceassembly \ microsoft \ windowspowershell中

private void button1_Click(object sender, EventArgs e)
{
  Runspace rs = RunspaceFactory.CreateRunspace();
  rs.Open();
  Pipeline pl = rs.CreatePipeline();
  pl.Commands.AddScript("get-wmiobject win32_share");

  StringBuilder sb = new StringBuilder();
  Collection<PSObject> list = pl.Invoke();
  rs.Close();
  foreach (PSObject obj in list)
  {
    string name = obj.Properties["Name"].Value as string;
    string path = obj.Properties["Path"].Value as string;
    string desc = obj.Properties["Description"].Value as string;

    sb.AppendLine(string.Format("{0}{1}{2}",name, path, desc));
  }
  // do something with the results...
}