需要建议访问asp.net中的远程机器

Nul*_*ter 0 c# asp.net

我想访问远程计算机上的某些位置.我想访问的文件夹可以完全控制每个人.下面给出的代码用于访问网络路径.

 System.IO.DirectoryInfo locationInfo = new System.IO.DirectoryInfo(BackupLocationTxt.Text);
        if (locationInfo.Exists)  
        {
            // do some operations
         }
Run Code Online (Sandbox Code Playgroud)

如果要访问的主机和远程计算机都有os windows xp,应用程序运行正常.如果应用程序在visual studio中运行,应用程序也运行正常.

然后我的问题是,机器(服务器和远程机器)中的任何一个具有更新的操作系统,然后是windows xp(如windows 7,server 2008),locationInfo.Exists总是为false.

但是如果应用程序在visual studio中运行,那么它可以独立于os工作

我在网上搜索了很多.但还没有找到确切的解决方案.有人建议冒充.但我不知道该怎么做.模仿是解决我的问题的方法吗?还是有更好的想法?

任何帮助将不胜感激

Phi*_*Fox 9

你有一个有趣的问题,Null.您是如何配置网站目录安全性的?如果启用了匿名访问,则打开Everyone的文件夹可能不允许访问,具体取决于服务器的操作系统(有关详细信息,请参阅Microsoft KB文章).

如果站点以匿名方式运行,则可以在IIS管理器中更改站点运行的帐户,也可以启用"模拟".当您在Visual Studio中运行该站点时,该站点正在运行您的权限,因此Anonymous不是问题.

您可以使用以下代码输出您的站点正在运行的用户的身份,以帮助确定正在进行的操作.您可以将用户的站点作为对网络位置的访问权限而不进行任何模拟.向您的页面添加ASP:Label并查看您的运行方式:

lblSomeLabel.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name
Run Code Online (Sandbox Code Playgroud)

模拟可能会给您带来额外的安全风险,因此您应该在进行更改之前进行更多阅读 - 但是,您用于模拟的用户不需要是域管理员.在您的情况下,用户可能只需要拥有网络位置的完全访问权限.

您可以阅读有关如何在此Microsoft KB文章上启用模拟的详细信息.以下是我推荐的该页面的一些代码.以下代码不是让您的整个网站以模拟模式运行,而是仅运行您遇到问题的部分.

public void Page_Load(Object s, EventArgs e)
{
    if(impersonateValidUser("username", "domain", "password"))
    {
        //Insert your code that runs under the security context of a specific user here.
        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();
}
Run Code Online (Sandbox Code Playgroud)

此外,在为安全性文章进行搜索时,我发现这个值得阅读的StackOverflow问题.