簡體   English   中英

如何使用C#共享文件夾和添加權限

[英]How to share a folder and add permissions with C#

我試圖共享一個文件夾及其內容,並以編程方式授予“所有人”讀寫權限。 它應該等效於下圖中的手動操作。

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

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

我嘗試了列出的代碼,但是它確實共享了該文件夾,但是沒有權限。 用戶能夠看到該文件夾​​,但是當他嘗試打開該文件夾時,他得到“權限被拒絕”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM