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

时间:2008-09-25 22:15:25

标签: c# .net windows

是否有办法通过.net框架确定文件夹是否共享?

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

我忘记提到的一件事是我想检查网络共享。但我会调查WMI的内容。

4 个答案:

答案 0 :(得分:9)

您可以使用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;

}

请注意,我在字节上link残酷地复制粘贴

答案 1 :(得分:4)

您可以使用WMI Win32_Share。 看看:

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

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

答案 2 :(得分:4)

使用powershell(如果安装了它)的另一种方法是使用powershell来调用wmi调用,包括对System.Management.Automation的引用,它最可能是在\ program files \ reference assemblies \微软\ 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...
}

答案 3 :(得分:0)

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