2015-05-12 13 views
0

我在我的電腦有兩個用戶帳戶C#訪問本地文件夾的管理員帳戶的憑據

用戶1(普通用戶)

聯繫

現在我的文件夾「ê :\ Folder1「只有管理員帳戶具有完全訪問權限。用戶!無法訪問該文件夾。

我有一個WPF應用程序它只能在用戶1帳戶內運行。我希望用戶1使用wpf應用程序訪問「Folder1」。

我想知道如何使用C#。

我試過以下它不起作用。

NetworkCredential theNetworkCredential = new NetworkCredential(@"admin", "pass"); 
      CredentialCache theNetCache = new CredentialCache(); 
      theNetCache.Add(new Uri(@"E:\SDAVideo"), "Basic", theNetworkCredential); 
      string[] theFolders = Directory.GetDirectories(@"E:\SDAVideo"); 

這是我都試過了。 使用下面的代碼,我能夠獲得管理員用戶帳戶的身份在Windows

SafeTokenHandle safeTokenHandle; 
     try 
     { 
      const int LOGON32_PROVIDER_DEFAULT = 0; 
      //This parameter causes LogonUser to create a primary token. 
      const int LOGON32_LOGON_INTERACTIVE = 2; 

      // Call LogonUser to obtain a handle to an access token. 
      bool returnValue = LogonUser("admin", "", "pass", 
       LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, 
       out safeTokenHandle); 
      if (false == returnValue) 
      { 
       int ret = Marshal.GetLastWin32Error(); 
       Debug.Write("\nLogonUser failed with error code : " + ret); 
       throw new System.ComponentModel.Win32Exception(ret); 
      } 
      using (safeTokenHandle) 
      { 
       Debug.Write("\nDid LogonUser Succeed? " + (returnValue ? "Yes" : "No")); 
       Debug.Write("\nValue of Windows NT token: " + safeTokenHandle); 

       // Check the identity. 
       Debug.Write("\nBefore impersonation: " 
        + WindowsIdentity.GetCurrent().Name); 
       Debug.Write("\nWriteAccess before: " + DirectoryHasPermission(@"E:\SDAVideo", WindowsIdentity.GetCurrent(), FileSystemRights.Write)); 
       // Use the token handle returned by LogonUser. 
       using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle())) 
       { 

        // Check the identity. 
        Debug.Write("\nAfter impersonation: " 
         + WindowsIdentity.GetCurrent().Name); 
        AccessFolder(WindowsIdentity.GetCurrent(), @"E:\SDAVideo"); 
        //Debug.Write("\nWriteAccess after: " + DirectoryHasPermission(@"E:\SDAVideo", WindowsIdentity.GetCurrent(), FileSystemRights.Write)); 
       } 
       // Releasing the context object stops the impersonation 
       // Check the identity. 
       Debug.Write("\nAfter closing the context: " + WindowsIdentity.GetCurrent().Name); 

      } 

     } 
     catch (Exception ex) 
     { 
      Debug.Write("\n1" + ex.ToString()); 
     } 

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid 
    { 
     private SafeTokenHandle() 
      : base(true) 
     { 
     } 

     [DllImport("kernel32.dll")] 
     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 
     [SuppressUnmanagedCodeSecurity] 
     [return: MarshalAs(UnmanagedType.Bool)] 
     private static extern bool CloseHandle(IntPtr handle); 

     protected override bool ReleaseHandle() 
     { 
      return CloseHandle(handle); 
     } 
    } 

public static bool DirectoryHasPermission(string DirectoryPath, WindowsIdentity identity, FileSystemRights AccessRight) 
    { 
     //if (string.IsNullOrEmpty(DirectoryPath)) return false; 

     try 
     { 
      AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); 
      //WindowsIdentity identity = WindowsIdentity.GetCurrent(); 
      Debug.Write("\nUSER: " + identity.Name); 
      foreach (FileSystemAccessRule rule in rules) 
      { 
       if (identity.Groups.Contains(rule.IdentityReference)) 
       { 
        if ((AccessRight & rule.FileSystemRights) == AccessRight) 
        { 
         if (rule.AccessControlType == AccessControlType.Allow) 
          return true; 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Debug.Write("\n2 " + ex.ToString()); 
     } 
     return false; 
    } 

public static void AccessFolder(WindowsIdentity identity, string DirectoryPath) 
    { 
     try 
     { 
      Debug.Write("\nUSER: " + identity.Name); 
      DirectoryInfo myDirectoryInfo = new DirectoryInfo(DirectoryPath); 
      DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl(); 

      myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(identity.Name, FileSystemRights.Write, AccessControlType.Allow)); 

      myDirectoryInfo.SetAccessControl(myDirectorySecurity); 
      string pathString = System.IO.Path.Combine(DirectoryPath, "test.txt"); 
      if (!System.IO.File.Exists(pathString)) 
      { 
       using (System.IO.FileStream fs = System.IO.File.Create(pathString)) 
       { 
        for (byte i = 0; i < 100; i++) 
        { 
         fs.WriteByte(i); 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      Debug.Write("\n3 " + ex.ToString()); 
     } 
    } 

錯誤,我得到如下 System.UnauthorizedAccessException的:嘗試執行未經授權的操作。

System.InvalidOperationException:出現意外錯誤代碼1346


所有這些失敗的方法失敗,唯一的事情,我能夠做的就是順利拿到管理員用戶的Windows標識。 現在,我需要解決這兩個問題 1.如何檢查應用程序是否使用管理的Windows標識寫入訪問 2.如果是這樣如何寫入文件夾的東西。

+0

看一看這個QA(http://stackoverflow.com/questions/125341/how-do-you-do [你如何在.NET中做模擬?] - 在網絡中) –

+0

謝謝夥伴,我用我試過的道具更新了我的問題。 –

+0

您是否看過該QA中的[最上面的回答](http://stackoverflow.com/a/7250145/3864353)並試用了Matt Johnson創建的軟件包? –

回答

0

試一下:

using System; 
using System.IO; 
using System.Security.AccessControl; 

namespace MyWpfApplication 
{ 
    public class AccessRules 
    { 
     private void SetAccessRuleForCurrentUser() 
     { 
      DirectoryInfo myDirectoryInfo = new DirectoryInfo(@"e:\Folder1"); 
      DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl(); 

      myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(System.Security.Principal.WindowsIdentity.GetCurrent().Name, FileSystemRights.Read, AccessControlType.Allow)); 

      myDirectoryInfo.SetAccessControl(myDirectorySecurity); 
     } 
    } 
} 
+0

感謝您的幫助。我試過你並更新了結果。我獲得了管理員帳戶的Windows身份。現在我需要使用管理員帳戶窗口標識寫入文件夾。 –

相關問題