【问题标题】:Access remote directory from another domain with c#使用 c# 从另一个域访问远程目录
【发布时间】:2016-07-07 19:44:13
【问题描述】:

我需要访问从另一个域中找到的以下目录到我的 c# 程序中。我该如何进行?我应该使用 Impersonate 方法吗?

string[] files = Directory.GetFiles(@"\\testweb\folder\test", "*.txt");

请帮忙。

【问题讨论】:

    标签: c# directory remote-access impersonation


    【解决方案1】:

    在执行此操作之前,您需要以编程方式(如果您想解决此问题)使用适当的用户创建与域的连接。您可以使用此类:

       public class MprWrapper
        {
            [DllImport("Mpr.dll")]
            private static extern int WNetUseConnection(
                IntPtr hwndOwner,
                _NETRESOURCE lpNetResource,
                string lpPassword,
                string lpUserID,
                int dwFlags,
                string lpAccessName,
                string lpBufferSize,
                string lpResult
                );
    
            struct _NETRESOURCE
            {
                public int dwScope;
                public int dwType;
                public int dwDisplayType;
                public int dwUsage;
                public string lpLocalName;
                public string lpRemoteName;
                public string lpComment;
                public string lpProvider;
            }
    
    
            public static void WNetUseConnection(string remoteName, string user, string pass)
            {
                _NETRESOURCE myStruct = new _NETRESOURCE
                {
                    dwType = 1, //it's a disk (0 is any, 2 is printer)
                    lpRemoteName = remoteName
                };
    
                int error = WNetUseConnection(new IntPtr(0), myStruct, pass, user, 0, null, null, null);
                if (error != 0)
                {
                    throw new Exception("That didn't work either");
                }
                // if we reach here then everything worked!!!
            }
        }
    

    你与

     MprWrapper.WNetUseConnection(@"\\DomainAddressHere", @"Domain\User", "Password1");
    

    那么你的 getfiles 方法就可以正常工作了。这可能会留下一个打开的连接(但它不会创建多个),但无论如何您可能想要创建代码来关闭它、正确处理所有内容等。这只是一个起点。

    【讨论】:

    • 我应该在哪里创建这个连接?
    • @velvt 在调用方法之前
    猜你喜欢
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    相关资源
    最近更新 更多