2007年5月3日 星期四

[C#] 利用 WMI 完成 Windows 資料夾分享

MSN SpaceGoogle DocGoogle Blog啪啦資訊科技
Chui-Wen Chiu(Arick)
2007.05.03 建立

[1] 提出利用 WMI 快速完成特定資料夾分享的方式,整個概念的核心程式碼如下:

using System;
using System.Management;

namespace ConsoleApplication1 {
class Program {

// 測試片段,將 c:perl 目錄設定為共用
static void Main(string[] args) {
QshareFolder("c:\Perl", "Test Share", "This is a Test Share");
}

// WMI 建立 Windows 資料夾分享

private static void QshareFolder(string FolderPath, string ShareName, string Description) {
try {
// 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"] = Description;
inParams["Name"] = ShareName;
inParams["Path"] = FolderPath;

inParams["Type"] = 0x0; // Disk Drive

//Another Type:
// DISK_DRIVE = 0x0
// PRINT_QUEUE = 0x1
// DEVICE = 0x2
// IPC = 0x3
// DISK_DRIVE_ADMIN = 0x80000000
// PRINT_QUEUE_ADMIN = 0x80000001
// DEVICE_ADMIN = 0x80000002
// IPC_ADMIN = 0x8000003
// inParams["MaximumAllowed"] = int maxConnectionsNum;
// 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.");
}

} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}
}



執行結果:


參考資料:
[1] How to Share Windows Folders Using C#

沒有留言:

搜尋此網誌