1 public class ShareFolder 2 { 3 private static readonly DictionaryReturnDetails = new Dictionary (); 4 5 /// 6 /// Success (0) 7 /// Access denied (2) 8 /// Unknown failure (8) 9 /// Invalid name (9)10 /// Invalid level (10)11 /// Invalid parameter (21)12 /// Duplicate share (22)13 /// Redirected path (23)14 /// Unknown device or directory (24)15 /// Net name not found (25)16 /// Other (26–4294967295)17 /// 18 static ShareFolder()19 {20 ReturnDetails.Add(0, "Success");21 ReturnDetails.Add(2, "Access denied");22 ReturnDetails.Add(8, "Unknown failure");23 ReturnDetails.Add(9, "Invalid name");24 ReturnDetails.Add(10, "Invalid level");25 ReturnDetails.Add(21, "Invalid parameter");26 ReturnDetails.Add(22, "Duplicate share");27 ReturnDetails.Add(23, "Redirected path");28 ReturnDetails.Add(24, "Unknown device or directory");29 ReturnDetails.Add(25, "Net name not found");30 }31 32 ///33 /// 设置文件夹共享 34 /// 35 /// 文件夹路径 36 /// 共享名 37 /// 共享注释38 ///39 public static void Share(string folderPath, string shareName, string description)40 {41 var directoryInfo = new DirectoryInfo(folderPath);42 DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();43 directorySecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.FullControl,44 InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));45 directoryInfo.SetAccessControl(directorySecurity);46 47 var managementClass = new ManagementClass("Win32_Share");48 // Create ManagementBaseObjects for in and out parameters 49 ManagementBaseObject inParams = managementClass.GetMethodParameters("Create");50 ManagementBaseObject outParams;51 // Set the input parameters 52 inParams["Description"] = description;53 inParams["Name"] = shareName;54 inParams["Path"] = folderPath;55 inParams["Type"] = 0; // Disk Drive 56 inParams["MaximumAllowed"] = null;57 inParams["Password"] = null;58 inParams["Access"] = null; // Make Everyone has full control access.59 outParams = managementClass.InvokeMethod("Create", inParams, null);60 // Check to see if the method invocation was successful 61 uint result = (uint)(outParams.Properties["ReturnValue"].Value);62 63 if (result != 0)64 {65 if (ReturnDetails.ContainsKey(result))66 {67 throw new Exception(ReturnDetails[result]);68 }69 else70 {71 throw new Exception("failed to create share folder");72 }73 }74 }75 }
//测试
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 string folderPath = @"C:\SML\ShareFolder7"; 6 7 //创建文件夹 8 if (!Directory.Exists(folderPath)) 9 {10 Directory.CreateDirectory(folderPath);11 }12 13 ShareFolder.Share(folderPath, "共享文件7", "共享注释");14 15 16 }17 }