本文介绍了如何通过使用管理员凭据来更改文件夹权限,当前用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我一直在寻找了一段时间,标题解释了pretty很多我想做的事情。
另外,是没有问题的硬编码的管理员凭据在code。

起初我写在C#中的一些code,几乎解决了这个问题:

 私人无效button2_Click(对象发件人,EventArgs的发送)
    {        DirectoryInfo的myDirectoryInfo =新DirectoryInfo的(textBox1.Text);        DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
        字符串USER = System.Environment.UserDomainName +\\\\+ comboBox1.SelectedItem.ToString();
        myDirectorySecurity.AddAccessRule(新FileSystemAccessRule(用户,FileSystemRights.FullControl,InheritanceFlags.ContainerInherit,PropagationFlags.None,AccessControlType.Allow));        //myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(用户,FileSystemRights.Write,InheritanceFlags.ContainerInherit,PropagationFlags.None,AccessControlType.Allow));        myDirectoryInfo.SetAccessControl(myDirectorySecurity);
        MessageBox.Show(权限成功改变的+用户);    }

如果我的文件夹,我已经有权限上使用这只是正常的,但我需要的是一个使用管理员凭据授予权限,以一个普通用户没有一个文件夹的方法。

后来我试着写在VBScript中的一些东西:

  strHomeFolder =C:\\测试
strUser的=域\\用户设置的WshShell =的CreateObject(WScript.Shell)WshShell.Run%COMSPEC%/℃回声Y | CACLS&放大器; strHomeFolder&安培; / E / C / G&放大器; strUser的&安培;:F,2,真

但我无法找到一个方法来传递管理员凭据。
所以最后我写了另一个code,试图把它做:

 私人无效的button1_Click(对象发件人,EventArgs的发送)
    {
        尝试
        {
            //字符串密码pre =密码;
            //的char [] = passwordChars密码pre.ToCharArray();
            // SecureString的密码=新SecureString的();
            //的foreach(在passwordChars字符C)
            // {
            // password.AppendChar(C);
            //}
            的ProcessStartInfo P =新的ProcessStartInfo(@D:\\\\ test.vbs);
            //p.UseShellExecute = FALSE;
            //p.UserName =用户名;
            //p.Domain =DOMAIN;            //p.Password =密码;
            的Process.Start(P);
        }
        赶上(异常前)
        {
            MessageBox.Show(ex.Message);
        }
    }

这时候我只是想用一个过程来传递管理员凭据,但它产生的消息:指定的可执行文件是不是该操作系统plataform有效的应用程序

那么,有没有我可以用它来传递任何凭据的方法? (可在C#或VBScript)。

先谢谢了。


解决方案

模拟将解决你的问题。当您在模拟环境中执行code,放置在上下文中的逻辑将模拟用户的previlege执行。继类从web.config文件reards的模拟配置值。您可以修改它的app.config或任何源读取。

所需的配置


  1. 用户名

  2. 密码

  3. 域名

 public class Impersonator : IDisposable
    {
        #region Win32 Advanced API calls

        /// <summary>
        /// Logons the user.
        /// </summary>
        /// <param name="lpszUserName">Name of the LPSZ user.</param>
        /// <param name="lpszDomain">The LPSZ domain.</param>
        /// <param name="lpszPassword">The LPSZ password.</param>
        /// <param name="dwLogOnType">Type of the dw log on.</param>
        /// <param name="dwLogOnProvider">The dw log on provider.</param>
        /// <param name="phToken">The ph token.</param>
        /// <returns></returns>
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true,
            BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern int LogonUser(String lpszUserName,
                String lpszDomain,
                String lpszPassword,
                int dwLogOnType,
                int dwLogOnProvider,
                ref IntPtr phToken);

        /// <summary>
        /// Duplicates the token.
        /// </summary>
        /// <param name="hToken">The h token.</param>
        /// <param name="impersonationLevel">The impersonation level.</param>
        /// <param name="hNewToken">The h new token.</param>
        /// <returns></returns>
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true,
            BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern int DuplicateToken(IntPtr hToken,
                int impersonationLevel,
                ref IntPtr hNewToken);

        /// <summary>
        /// Reverts to self.
        /// </summary>
        /// <returns></returns>
        [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true,
            BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern bool RevertToSelf();


        /// <summary>
        /// Closes the handle.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <returns></returns>
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true,
            BestFitMapping = false, ThrowOnUnmappableChar = true)]
        private static extern bool CloseHandle(IntPtr handle);

        #endregion

        #region Fields

        /// <summary>
        /// Field to hold the impersonation Context
        /// </summary>
        WindowsImpersonationContext impersonationContext;

        /// <summary>
        /// Track whether Dispose has been called.
        /// </summary>
        private bool disposed;

        #region Constants
        /// <summary>
        /// Logon32 Logon Interactive 
        /// </summary>
        public const int INTERACTIVE_NUMBER = 2;

        /// <summary>
        /// Logon32 Provider Default
        /// </summary>
        public const int DEFAULT_NUMBER = 0;

        /// <summary>
        /// Impersonating user name key
        /// </summary>
        public const string ImpersonatingUserNameKey = "ImpersonatingUserName";

        /// <summary>
        /// Impersonating user password key
        /// </summary>
        public const string ImpersonatingPasswordKey = "ImpersonatingUserPassword";

        /// <summary>
        /// Impersonating user domain key
        /// </summary>
        public const string ImpersonatingDomainNameKey = "ImpersonatingDomain";

        #endregion

        #endregion

        #region Construction/Destruction/Initialization

        /// <summary>
        /// Constructor of the impersonator
        /// </summary>
        public Impersonator()
        {
            if (!ImpersonateUser(ConfigurationManager.AppSettings[ImpersonatingUserNameKey],
                                    ConfigurationManager.AppSettings[ImpersonatingDomainNameKey],
                                    ConfigurationManager.AppSettings[ImpersonatingPasswordKey]))
            {
                //TODO: Log Exception
            }
        }

        #endregion

        #region Public Methods

        // Implement IDisposable.
        // Do not make this method virtual.
        // A derived class should not be able to override this method.
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method.
            // Therefore, you should call GC.SupressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Impersonate User with the given user credentials
        /// </summary>
        /// <param name="userName">User Name</param>
        /// <param name="domain">Domain</param>
        /// <param name="password">Password</param>
        /// <returns>True if success, false otherwise</returns>
        private bool ImpersonateUser(String userName, String domain, String password)
        {
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
            {
                if (LogonUser(userName, domain, password, INTERACTIVE_NUMBER,
                        DEFAULT_NUMBER, ref token) != 0)
                {
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                        {
                            CloseHandle(token);
                            CloseHandle(tokenDuplicate);
                            return true;
                        }
                    }
                }
            }
            if (token != IntPtr.Zero)
                CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero)
                CloseHandle(tokenDuplicate);
            return false;
        }

        /// <summary>
        /// Undo impersonation
        /// </summary>
        private void StopImpersonation()
        {
            impersonationContext.Undo();
        }

        #endregion

        #region Protected Methods

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    StopImpersonation();
                }

                // Note disposing has been done.
                disposed = true;
            }
        }

        #endregion
    }
Using(Impersonator impersonator = new Impersonator())
{
  //Write the folder accessing logic here
}

这篇关于如何通过使用管理员凭据来更改文件夹权限,当前用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 19:54