[英]Copying file to shared drive fails in ASP.net c#
我有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)
{
}
}
您可以像这样设置模拟用户类:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.