zl程序教程

您现在的位置是:首页 >  后端

当前栏目

asp.net实现访问局域网共享目录下文件的解决方法

Net文件ASP方法 实现 解决 访问 目录
2023-06-13 09:15:38 时间

本文以实例讲述了asp.net实现访问局域网共享目录下文件的解决方法,完整代码如下所示:

usingSystem;
usingSystem.Collections;
usingSystem.Configuration;
usingSystem.Data;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.HtmlControls;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Xml.Linq;
usingSystem.IO;
usingSystem.Security.Principal;
usingSystem.Runtime.InteropServices;
publicpartialclass_Default:System.Web.UI.Page
{
publicconstintLOGON32_LOGON_INTERACTIVE=2;
publicconstintLOGON32_PROVIDER_DEFAULT=0;
WindowsImpersonationContextimpersonationContext;
[DllImport("advapi32.dll")]
publicstaticexternintLogonUserA(StringlpszUserName,
StringlpszDomain,
StringlpszPassword,
intdwLogonType,
intdwLogonProvider,
refIntPtrphToken);
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
publicstaticexternintDuplicateToken(IntPtrhToken,
intimpersonationLevel,
refIntPtrhNewToken);
[DllImport("advapi32.dll",CharSet=CharSet.Auto,SetLastError=true)]
publicstaticexternboolRevertToSelf();
[DllImport("kernel32.dll",CharSet=CharSet.Auto)]
publicstaticexternboolCloseHandle(IntPtrhandle);
publicvoidPage_Load(Objects,EventArgse)
{
if(impersonateValidUser("lucas","Workgroup","lcas"))
{
stringpath=@"//zhehui001/lu";
foreach(stringfinDirectory.GetFiles(path))
{
Response.Write(f);
}
undoImpersonation();
}
else
{
//Yourimpersonationfailed.Therefore,includeafail-safemechanismhere.
}
}
privateboolimpersonateValidUser(StringuserName,Stringdomain,Stringpassword)
{
WindowsIdentitytempWindowsIdentity;
IntPtrtoken=IntPtr.Zero;
IntPtrtokenDuplicate=IntPtr.Zero;
if(RevertToSelf())
{
if(LogonUserA(userName,domain,password,LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT,reftoken)!=0)
{
if(DuplicateToken(token,2,reftokenDuplicate)!=0)
{
tempWindowsIdentity=newWindowsIdentity(tokenDuplicate);
impersonationContext=tempWindowsIdentity.Impersonate();
if(impersonationContext!=null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
returntrue;
}
}
}
}
if(token!=IntPtr.Zero)
CloseHandle(token);
if(tokenDuplicate!=IntPtr.Zero)
CloseHandle(tokenDuplicate);
returnfalse;
}
privatevoidundoImpersonation()
{
impersonationContext.Undo();
}
}