如何共享文件夹并使用C#添加权限

时间:2014-11-09 12:10:31

标签: c# vb.net

我正在尝试共享文件夹及其内容,并以编程方式为“Everyone”提供读/写权限。 它应该等同于以下图像中的手动操作。

http://imageshack.com/a/img910/7316/XiLb1E.png

http://imageshack.com/a/img674/7982/jhdQrw.png

我尝试了列出的代码,但它确实共享了该文件夹,但没有权限。用户可以看到该文件夹​​,但当他试图打开它时,他会得到“Permission Denied”。

Private Sub ShearFolder()

    Dim DI As DirectoryInfo = New DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) & "DB")
    Dim Ds As DirectorySecurity = DI.GetAccessControl()
    Ds.AddAccessRule(New FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow))
    DI.SetAccessControl(Ds)

    Dim MC As ManagementClass = New ManagementClass("Win32_Share")

    Dim inParam As ManagementBaseObject = MC.GetMethodParameters("Create")
    Dim OutParam As ManagementBaseObject

    inParam("Description") = "DB"
    inParam("Name") = "DB"
    inParam("Path") = AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) & "DB"
    inParam("Type") = 0
    inParam("MaximumAllowed") = Nothing
    inParam("Access") = Nothing

    outParam = MC.InvokeMethod("create", inParam, Nothing)

    Dim ntAccount As NTAccount = New NTAccount("Everyone")

    Dim userSID As SecurityIdentifier = ntAccount.Translate(GetType(SecurityIdentifier))

    Dim utenteSIDArray(userSID.BinaryLength) As Byte
    userSID.GetBinaryForm(utenteSIDArray, 0)

    Dim userTrustee As ManagementObject = New ManagementClass(New ManagementPath("Win32_Trustee"), Nothing)
    userTrustee("Name") = "Everyone"
    userTrustee("SID") = utenteSIDArray

    Dim userACE As ManagementObject = New ManagementClass(New ManagementPath("Win32_Ace"), Nothing)
    userACE("AccessMask") = 2032127                                
    userACE("AceFlags") = AceFlags.ObjectInherit
    userACE("AceType") = AceType.AccessAllowed
    userACE("Trustee") = userTrustee


    Dim userSecurityDescriptor As ManagementObject = New ManagementClass(New ManagementPath("Win32_SecurityDescriptor"), Nothing)
    userSecurityDescriptor("ControlFlags") = 4 
    userSecurityDescriptor("DACL") = New Object() {userACE}

    MC = New ManagementClass("Win32_Share")
    Dim share As ManagementObject = New ManagementObject(AppDomain.CurrentDomain.BaseDirectory.Substring(0, AppDomain.CurrentDomain.BaseDirectory.IndexOf("bin")) & "DB" & ".Name='DB'")
    share.InvokeMethod("SetShareInfo", New Object() {Int32.MaxValue, "DB", userSecurityDescriptor})

End Sub

1 个答案:

答案 0 :(得分:0)