C#通过WMI操作本地共享文件夹
WMI是Windows Management Instrumentation的缩写。它提供能非常强大的功能,比如:主板、BIOS、内存、磁盘、网络等的操作。
详情参考:http://msdn.microsoft.com/en-us/library/aa384642(VS.85).aspx
这里只是备注一下如何操作本地共享文件夹。
共享文件夹大家都应该比较熟悉:共享音乐,电影,游戏,文档什么的给其他人使用。
非常简单的在Explorer里面就可以实现了,不过我常常是共享了一些文件夹,用完以后忘了取消共享。时间长了以后就忘了共享的文件夹具体是在什么地方了。而如果你直接删掉了共享的文件,而没有取消共享的话,其他人还是能看到看到这个文件夹,但是不能访问里面的内容了。
我就在想,windows就没有提供这个功能来取消共享文件夹或者找到共享文件夹的实际路径吗?可能是我不知道而已……
google了一下,发现可以通过WMI来获得共享文件的信息并取消共享
关于如何获得所有本地共享文件夹的代码:
pubilc const uint DISK_DRIVE = 0x0;
pubilc const uint PRINT_QUEUE = 0x1;
pubilc const uint DEVICE = 0x2;
pubilc const uint IPC = 0x3;
pubilc const uint DISK_DRIVE_ADMIN = 0x80000000;
pubilc const uint PRINT_QUEUE_ADMIN = 0x80000001;
pubilc const uint DEVICE_ADMIN = 0x80000002;
pubilc const uint IPC_ADMIN = 0x80000003;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Share");
foreach (ManagementObject queryObj in searcher.Get())
{
uint type = uint.Parse(queryObj["Type"].ToString());
if (DISK_DRIVE != type)
{
continue;
}
FolderInformation info = new FolderInformation();
info.Name = queryObj["Name"].ToString();
info.Path = queryObj["Path"].ToString();
info.Description = queryObj["Description"].ToString();
folderList.Add(info);
}
pubilc const uint PRINT_QUEUE = 0x1;
pubilc const uint DEVICE = 0x2;
pubilc const uint IPC = 0x3;
pubilc const uint DISK_DRIVE_ADMIN = 0x80000000;
pubilc const uint PRINT_QUEUE_ADMIN = 0x80000001;
pubilc const uint DEVICE_ADMIN = 0x80000002;
pubilc const uint IPC_ADMIN = 0x80000003;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Share");
foreach (ManagementObject queryObj in searcher.Get())
{
uint type = uint.Parse(queryObj["Type"].ToString());
if (DISK_DRIVE != type)
{
continue;
}
FolderInformation info = new FolderInformation();
info.Name = queryObj["Name"].ToString();
info.Path = queryObj["Path"].ToString();
info.Description = queryObj["Description"].ToString();
folderList.Add(info);
}
取消共享也很简单
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Share WHERE Name = '" + sharingName + "'");
foreach (ManagementObject queryObj in searcher.Get())
{
uint type = uint.Parse(queryObj["Type"].ToString());
if (DISK_DRIVE != type)
{
continue;
}
queryObj.InvokeMethod("Delete", null, null);
}
foreach (ManagementObject queryObj in searcher.Get())
{
uint type = uint.Parse(queryObj["Type"].ToString());
if (DISK_DRIVE != type)
{
continue;
}
queryObj.InvokeMethod("Delete", null, null);
}