我有ASP.Net和C#应用程序。我正在将图像上传到网站并将其存储在C:\Images
目录中,这样可以正常工作。当我将图像保存到C:\Images
文件夹并同时复制(或有时移动)到共享驱动器时,我使用共享驱动器物理地址,比如\\192.xxx.x.xx\some folder\Images
。此驱动器映射到部署服务器。我正在为该网站使用IIS托管。
问题在于共享驱动器复制。当我从本地计算机(部署站点)使用该站点时,会将该文件复制到共享驱动器。但是当我从另一台机器(部署的服务器除外)使用该站点时,该站点将图像保存在C:\Images
中,但它不会将文件复制到共享驱动器。
这是我正在使用的代码
** Loggedon方法显示调试成功。
public static void CopytoNetwork(String Filename)
{
try
{
string updir = System.Configuration.ConfigurationManager.AppSettings["PhysicalPath"].ToString();
WindowsImpersonationContext impersonationContext = null;
IntPtr userHandle = IntPtr.Zero;
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
String UserName = System.Configuration.ConfigurationManager.AppSettings["Server_UserName"].ToString();
String Password = System.Configuration.ConfigurationManager.AppSettings["server_Password"].ToString();
String DomainName = System.Configuration.ConfigurationManager.AppSettings["Server_Domain"].ToString();
bool loggedOn = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref userHandle);
try
{
File.Move(@"C:\Images\" + Filename, updir + "\\" + Filename);
}
catch (Exception)
{
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
}
}
}
catch (Exception)
{
}
}
答案 0 :(得分:1)
您可以设置这样的模拟用户类:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Security.Principal;
public class ImpersonatedUser : IDisposable
{
IntPtr userHandle;
WindowsImpersonationContext impersonationContext;
public ImpersonatedUser(string user, string domain, string password)
{
userHandle = IntPtr.Zero;
bool loggedOn = LogonUser(
user,
domain,
password,
LogonType.Interactive,
LogonProvider.Default,
out userHandle);
if (!loggedOn)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Begin impersonating the user
impersonationContext = WindowsIdentity.Impersonate(userHandle);
}
public void Dispose()
{
if (userHandle != IntPtr.Zero)
{
CloseHandle(userHandle);
userHandle = IntPtr.Zero;
impersonationContext.Undo();
}
}
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
LogonType dwLogonType,
LogonProvider dwLogonProvider,
out IntPtr phToken
);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hHandle);
enum LogonType : int
{
Interactive = 2,
Network = 3,
Batch = 4,
Service = 5,
NetworkCleartext = 8,
NewCredentials = 9,
}
enum LogonProvider : int
{
Default = 0,
}
}
当你需要进行文件复制时,你可以这样做:
using (new ImpersonatedUser(<UserName>, <UserDomainName>, <UserPassword>))
{
DoYourFileCopyLogic();
}