首页 新闻 搜索 专区 学院

使用 角色(用户)模拟 方式访问共享文件后怎么打开文件

0
悬赏园豆:60 [待解决问题]

主要使用了 advapi32.dll 和 kernel32.dll 来进行用户模拟, 可以对文件进行复制操作(比如将共享文件复制到本地磁盘 D), 但是无法直接打开任何共享文件, 如 .jpg 和 .doc

示例 : Process.Start(@"\\192.168.7.99\testpath\测试目录\测试文档.doc");

执行上述代码会报错, 登录失败: 未知的用户名或错误密码

 

以下为模拟用户代码

public class IdentityScope : IDisposable
    {
        // obtains user token     
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
            int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        // closes open handes returned by LogonUser     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        extern static bool CloseHandle(IntPtr handle);

        [DllImport("Advapi32.DLL")]
        static extern bool ImpersonateLoggedOnUser(IntPtr hToken);

        [DllImport("Advapi32.DLL")]
        static extern bool RevertToSelf();
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_NEWCREDENTIALS = 9;//域控中的需要用:Interactive = 2     
        private bool disposed;
        public IdentityScope(string sUsername, string sPassword, string sDomain)
        {
            // initialize tokens     
            IntPtr pExistingTokenHandle = new IntPtr(0);
            IntPtr pDuplicateTokenHandle = new IntPtr(0);

            try
            {
                // get handle to token     
                bool bImpersonated = LogonUser(sUsername, sDomain, sPassword,
                    LOGON32_LOGON_NEWCREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref pExistingTokenHandle);

                if (true == bImpersonated)
                {
                    if (!ImpersonateLoggedOnUser(pExistingTokenHandle))
                    {
                        int nErrorCode = Marshal.GetLastWin32Error();
                        throw new Exception("ImpersonateLoggedOnUser error;Code=" + nErrorCode);
                    }
                }
                else
                {
                    int nErrorCode = Marshal.GetLastWin32Error();
                    throw new Exception("LogonUser error;Code=" + nErrorCode);
                }
            }
            finally
            {
                // close handle(s)     
                if (pExistingTokenHandle != IntPtr.Zero)
                    CloseHandle(pExistingTokenHandle);
                if (pDuplicateTokenHandle != IntPtr.Zero)
                    CloseHandle(pDuplicateTokenHandle);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                RevertToSelf();
                disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
valesail的主页 valesail | 初学一级 | 园豆:142
提问于:2018-03-15 10:47
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册