【问题标题】:How to open file by specific user如何按特定用户打开文件
【发布时间】:2013-02-22 04:39:03
【问题描述】:

如何使用 .Net 打开特定用户的文件。
示例:

File.OpenFile(filePath, user)

【问题讨论】:

  • 请澄清:您要使用特定用户的凭据打开文件吗?
  • .NET 框架中不存在此方法。更具体地说明您想要完成的任务,而不是您想要使用的方法。
  • 我只是想检查用户是否可以打开/读取文件。 (任何用户不仅登录用户)

标签: .net


【解决方案1】:

来自this线程:

const string file = @"\\machine\test\file.txt";

        using (UserImpersonation2 user = new UserImpersonation2("user", "domain", "password"))
        {
            if (user.ImpersonateValidUser())
            {
                StreamReader reader = new StreamReader(file);
                Console.WriteLine(reader.ReadToEnd());
                reader.Close();
            }
        }


class UserImpersonation2:IDisposable
{
    [DllImport("advapi32.dll")]
    public static extern bool LogonUser(String lpszUserName,
        String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public static extern bool CloseHandle(IntPtr handle);

    WindowsImpersonationContext wic;
    IntPtr tokenHandle;
    string _userName;
    string _domain;
    string _passWord;

    public UserImpersonation2(string userName, string domain, string passWord)
    {
        _userName = userName;
        _domain = domain;
        _passWord = passWord;
    }

    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_LOGON_INTERACTIVE = 2;

    public bool ImpersonateValidUser()
    {
        bool returnValue = LogonUser(_userName, _domain, _passWord,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

        Console.WriteLine("LogonUser called.");

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            Console.WriteLine("LogonUser failed with error code : {0}", ret);
            return false;
        }

        Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
        Console.WriteLine("Value of Windows NT token: " + tokenHandle);

        // Check the identity.
        Console.WriteLine("Before impersonation: "
            + WindowsIdentity.GetCurrent().Name);
        // Use the token handle returned by LogonUser.
        WindowsIdentity newId = new WindowsIdentity(tokenHandle);
        wic = newId.Impersonate();

        // Check the identity.
        Console.WriteLine("After impersonation: "
            + WindowsIdentity.GetCurrent().Name);
        return true;
    }
    #region IDisposable Members
    public void Dispose()
    {
        if(wic!=null)
            wic.Undo();
        if (tokenHandle != IntPtr.Zero)
            CloseHandle(tokenHandle);

    }
    #endregion
}

【讨论】:

  • 我习惯使用 advapi32.dll 作为您的建议。但是如果有任何继承的权限,它总是抛出异常。
猜你喜欢
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2018-01-02
相关资源
最近更新 更多