欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 12:50:28
本文以实例讲述了asp.net实现访问局域网共享目录下文件的解决方法,完整代码如下所示: using system; using system.collect...

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

using system; 
using system.collections; 
using system.configuration; 
using system.data; 
using system.linq; 
using system.web; 
using system.web.security; 
using system.web.ui; 
using system.web.ui.htmlcontrols; 
using system.web.ui.webcontrols; 
using system.web.ui.webcontrols.webparts; 
using system.xml.linq; 
using system.io; 
using system.security.principal; 
using system.runtime.interopservices; 
public partial class _default : system.web.ui.page 
{ 
  public const int logon32_logon_interactive = 2; 
  public const int logon32_provider_default = 0; 
  windowsimpersonationcontext impersonationcontext; 
  [dllimport("advapi32.dll")] 
  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)] 
  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); 
  public void page_load(object s, eventargs e) 
  { 
    if (impersonatevaliduser("lucas", "workgroup", "lcas")) 
    { 
      string path = @"//zhehui001/lu"; 
      foreach (string f in directory.getfiles(path)) 
      { 
        response.write(f); 
      } 
      undoimpersonation(); 
    } 
    else 
    { 
      //your impersonation failed. therefore, include a fail-safe mechanism here. 
    } 
  } 
  private bool impersonatevaliduser(string username, string domain, string password) 
  { 
    windowsidentity tempwindowsidentity; 
    intptr token = intptr.zero; 
    intptr tokenduplicate = intptr.zero; 
    if (reverttoself()) 
    { 
      if (logonusera(username, domain, password, logon32_logon_interactive, 
        logon32_provider_default, ref token) != 0) 
      { 
        if (duplicatetoken(token, 2, ref tokenduplicate) != 0) 
        { 
          tempwindowsidentity = new windowsidentity(tokenduplicate); 
          impersonationcontext = tempwindowsidentity.impersonate(); 
          if (impersonationcontext != null) 
          { 
            closehandle(token); 
            closehandle(tokenduplicate); 
            return true; 
          } 
        } 
      } 
    } 
    if (token != intptr.zero) 
      closehandle(token); 
    if (tokenduplicate != intptr.zero) 
      closehandle(tokenduplicate); 
    return false; 
  } 
  private void undoimpersonation() 
  { 
    impersonationcontext.undo(); 
  } 
}