1 public class ShareFolder 2 { 3 private static readonly Dictionary<uint, string> ReturnDetails = new Dictionary<uint, string>(); 4 5 /// <summary> 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 /// </summary> 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 /// <summary> 33 /// 设置文件夹共享 34 /// </summary> 35 /// <param name="folderPath">文件夹路径</param> 36 /// <param name="shareName">共享名</param> 37 /// <param name="description">共享注释</param> 38 /// <returns></returns> 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 else 70 { 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:SMLShareFolder7"; 6 7 //创建文件夹 8 if (!Directory.Exists(folderPath)) 9 { 10 Directory.CreateDirectory(folderPath); 11 } 12 13 ShareFolder.Share(folderPath, "共享文件7", "共享注释"); 14 15 16 } 17 }