C#:如何在使用DirectoryInfo时登录共享
如果我想使用UNC路径实例化DirectoryInfo对象
DirectoryInfo myDI = new DirectoryInfo (@"\servershare");
如何传递访问该共享所需的用户名/密码?
谢谢
在.NET 4中,这个类非常适合我通过UNC登录无Windows服务器。
using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using System.Web; using System.Runtime.InteropServices; using System.Security.Principal; using System.Web.Security; namespace toolsforimpersonations { public class Impersonator { #region "Consts" public const int LOGON32_LOGON_INTERACTIVE = 2; public const int LOGON32_PROVIDER_DEFAULT = 0; #endregion #region "External API" [DllImport("advapi32.dll", SetLastError = true)] public static extern int LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool RevertToSelf(); [DllImport("kernel32.dll", SetLastError = true)] public static extern int CloseHandle(IntPtr hObject); #endregion #region "Methods" //Public Sub PerformImpersonatedTask(ByVal username As String, ByVal domain As String, ByVal password As String, ByVal logonType As Integer, ByVal logonProvider As Integer, ByVal methodToPerform As Action) public void PerformImpersonatedTask(string username, string domain, string password, int logonType, int logonProvider, Action methodToPerform) { IntPtr token = IntPtr.Zero; if (RevertToSelf()) { if (LogonUser(username, domain, password, logonType, logonProvider, ref token) != 0) { dynamic identity = new WindowsIdentity(token); dynamic impersonationContext = identity.Impersonate(); if (impersonationContext != null) { methodToPerform.Invoke(); impersonationContext.Undo(); } // do logging } else { } } if (token != IntPtr.Zero) { CloseHandle(token); } } #endregion } public class UserImpersonation { const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NETWORK = 3; const int LOGON32_LOGON_BATCH = 4; const int LOGON32_LOGON_SERVICE = 5; const int LOGON32_LOGON_UNLOCK = 7; const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; const int LOGON32_PROVIDER_DEFAULT = 0; const int LOGON32_PROVIDER_WINNT35 = 1; const int LOGON32_PROVIDER_WINNT40 = 2; const int LOGON32_PROVIDER_WINNT50 = 3; WindowsImpersonationContext impersonationContext; [DllImport("advapi32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] 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, ExactSpelling = true)] public static extern int DuplicateToken(IntPtr ExistingTokenHandle, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern long RevertToSelf(); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] public static extern long CloseHandle(IntPtr handle); public bool impersonateUser(string userName, string domain, string password) { return impersonateValidUser(userName, domain, password); } public void undoimpersonateUser() { undoImpersonation(); } private bool impersonateValidUser(string userName, string domain, string password) { bool functionReturnValue = false; WindowsIdentity tempWindowsIdentity = null; IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; functionReturnValue = false; //if (RevertToSelf()) { if (LogonUserA(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref token) != 0) { if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) { tempWindowsIdentity = new WindowsIdentity(tokenDuplicate); impersonationContext = tempWindowsIdentity.Impersonate(); if ((impersonationContext != null)) { functionReturnValue = true; } } } //} if (!tokenDuplicate.Equals(IntPtr.Zero)) { CloseHandle(tokenDuplicate); } if (!token.Equals(IntPtr.Zero)) { CloseHandle(token); } return functionReturnValue; } private void undoImpersonation() { impersonationContext.Undo(); } } }
这是如何使用您的程序
UserImpersonation impersonator = new UserImpersonation(); impersonator.impersonateUser("username", "", "password"); //No Domain is required List OcDialerlfinfo = null; OcDialerlfinfo = GetFileList("*", "\\10.11.11.122\shared_folder"); impersonator.undoimpersonateUser();
并且为了测试,您需要使用此小函数列出目录中的所有文件
public static List GetFileList(string fileSearchPattern, string rootFolderPath) { DirectoryInfo rootDir = new DirectoryInfo(rootFolderPath); List dirList = new List (rootDir.GetDirectories("*", SearchOption.AllDirectories)); dirList.Add(rootDir); List fileList = new List (); foreach (DirectoryInfo dir in dirList) { fileList.AddRange(dir.GetFiles(fileSearchPattern, SearchOption.TopDirectoryOnly)); } return fileList; }
试试这种方法:
上述就是C#学习教程:C#:如何在使用DirectoryInfo时登录共享分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.Principal; namespace Tools.Network { public enum LogonType { LOGON32_LOGON_INTERACTIVE = 2, LOGON32_LOGON_NETWORK = 3, LOGON32_LOGON_BATCH = 4, LOGON32_LOGON_SERVICE = 5, LOGON32_LOGON_UNLOCK = 7, LOGON32_LOGON_NETWORK_CLEARTEXT = 8, // Win2K or higher LOGON32_LOGON_NEW_CREDENTIALS = 9 // Win2K or higher }; public enum LogonProvider { LOGON32_PROVIDER_DEFAULT = 0, LOGON32_PROVIDER_WINNT35 = 1, LOGON32_PROVIDER_WINNT40 = 2, LOGON32_PROVIDER_WINNT50 = 3 }; public enum ImpersonationLevel { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3 } class Win32NativeMethods { [DllImport("advapi32.dll", SetLastError = true)] public static extern int LogonUser( 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); } /// /// Allows code to be executed under the security context of a specified user account. /// /// /// /// Implements IDispose, so can be used via a using-directive or method calls; /// ... /// /// var imp = new Impersonator( "myUsername", "myDomainname", "myPassword" ); /// imp.UndoImpersonation(); /// /// ... /// /// var imp = new Impersonator(); /// imp.Impersonate("myUsername", "myDomainname", "myPassword"); /// imp.UndoImpersonation(); /// /// ... /// /// using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) ) /// { /// ... /// [code that executes under the new context] /// ... /// } /// /// ... /// public class Impersonator : IDisposable { private WindowsImpersonationContext _wic; /// /// Begins impersonation with the given credentials, Logon type and Logon provider. /// /// Name of the user. /// Name of the domain. /// The password. /// Type of the logon. /// The logon provider. public Impersonator(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider) { Impersonate(userName, domainName, password, logonType, logonProvider); } /// /// Begins impersonation with the given credentials. /// /// Name of the user. /// Name of the domain. /// The password. public Impersonator(string userName, string domainName, string password) { Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT); } /// /// Initializes a new instance of the class. /// public Impersonator() {} /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// public void Dispose() { UndoImpersonation(); } /// /// Impersonates the specified user account. /// /// Name of the user. /// Name of the domain. /// The password. public void Impersonate(string userName, string domainName, string password) { Impersonate(userName, domainName, password, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT); } /// /// Impersonates the specified user account. /// /// Name of the user. /// Name of the domain. /// The password. /// Type of the logon. /// The logon provider. public void Impersonate(string userName, string domainName, string password, LogonType logonType, LogonProvider logonProvider) { UndoImpersonation(); IntPtr logonToken = IntPtr.Zero; IntPtr logonTokenDuplicate = IntPtr.Zero; try { // revert to the application pool identity, saving the identity of the current requestor _wic = WindowsIdentity.Impersonate(IntPtr.Zero); // do logon & impersonate if (Win32NativeMethods.LogonUser(userName, domainName, password, (int)logonType, (int)logonProvider, ref logonToken) != 0) { if (Win32NativeMethods.DuplicateToken(logonToken, (int)ImpersonationLevel.SecurityImpersonation, ref logonTokenDuplicate) != 0) { var wi = new WindowsIdentity(logonTokenDuplicate); wi.Impersonate(); // discard the returned identity context (which is the context of the application pool) } else throw new Win32Exception(Marshal.GetLastWin32Error()); } else throw new Win32Exception(Marshal.GetLastWin32Error()); } finally { if (logonToken != IntPtr.Zero) Win32NativeMethods.CloseHandle(logonToken); if (logonTokenDuplicate != IntPtr.Zero) Win32NativeMethods.CloseHandle(logonTokenDuplicate); } } /// /// Stops impersonation. /// private void UndoImpersonation() { // restore saved requestor identity if (_wic != null) _wic.Undo(); _wic = null; } } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1008125.html