我必须在指定用户的网络驱动器中创建许多文件。
我使用this answer来连接不同的用户 我使用Impersonator Class:
public class Impersonator : IDisposable
{
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport("advapi32.dll", SetLastError = true)]
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 extern static bool CloseHandle(IntPtr handle);
private IntPtr token = IntPtr.Zero;
private WindowsImpersonationContext impersonated;
private readonly string _ErrMsg = "";
public bool IsImpersonating
{
get { return (token != IntPtr.Zero) && (impersonated != null); }
}
public string ErrMsg
{
get { return _ErrMsg; }
}
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public Impersonator(string userName, string password, string domain)
{
StopImpersonating();
bool loggedOn = LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (!loggedOn)
{
_ErrMsg = new System.ComponentModel.Win32Exception().Message;
return;
}
WindowsIdentity identity = new WindowsIdentity(token);
impersonated = identity.Impersonate();
}
private void StopImpersonating()
{
if (impersonated != null)
{
impersonated.Undo();
impersonated = null;
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
token = IntPtr.Zero;
}
}
public void Dispose()
{
StopImpersonating();
}
}
和代码:
using (Impersonator impersonator = new Impersonator("UserName", "UserPwd", "UserDomaine"))
{
if (!Directory.Exists("Z:\\")) // check if Network drive exist
{
NetworkDrive drive = new NetworkDrive
{
ShareName = @"\\IP\Partage",
LocalDrive = "Z",
Force = true
};
drive.MapDrive(@"UserDomaine\UserName", "UserPwd");
}
File.Create(@"Z:\Log\FileName.txt");
}
但是在这种情况下,我发现每次我必须创建文件或更新它时代码映射驱动器!我有很多关于这个功能的工作。
有一个解决方案,不是每次都映射它吗?
我试图在启动应用程序时使用此用户映射驱动程序但同样的问题。
答案 0 :(得分:2)
我认为您不需要映射驱动器。模拟后,您可以直接使用网络驱动器创建文件,它将创建文件作为模拟用户。
using (Impersonator impersonator = new Impersonator("UserName", "UserPwd", "UserDomaine"))
{
File.Create(@"\\IP\Partage\Log\FileName.txt");
}
答案 1 :(得分:0)
尽量不要使用使用块。将Impersonator声明为全局静态变量。