如何使用窗口服务中的凭据从其他网络访问文件

时间:2014-08-07 06:54:51

标签: c#

我创建了一个窗口服务应用程序,它从其他网络读取文件,然后每隔1分钟将其保存到我的数据库中。我收到了一个用户名和密码,可以从其他网络访问该文件。不幸的是,我不知道如何使用网络用户名访问该文件。密码你能告诉我怎么做。谢谢。

我知道如何从app.config

提供文件的路径
  

的appSettings

     
    

add key =“filepath”value =“\ 111.111.1.11 \ dummyfolder \”

  

通过以下方式访问我的代码:

string path = ConfigurationManager.AppSettings["filepath"].ToString();

1 个答案:

答案 0 :(得分:0)

什么可以更容易?

class AuthHelper
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        [DllImport("advapi32.dll")]
        public static extern int LogonUserA(String lpszUserName,
            String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken,
            int impersonationLevel,
            ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

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

        public static WindowsIdentity GetWindowsIdentityForUser(String userName, String password, String domain)
        {
            WindowsIdentity result = null;

            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;

            if (RevertToSelf())
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                    {
                        result = new WindowsIdentity(tokenDuplicate);
                        if (result != null) return result;
                    }

            if (token != IntPtr.Zero) CloseHandle(token);
            if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);

            return result;
        }
    }

然后只是:

var identity = AuthHelper.GetWindowsIdentityForUser("other user", "password", "domain");
            using (var context = identity.Impersonate())
            {
                //do whatever you want as "other user"
            }