2016-07-07 31 views
0

我需要訪問從另一個域中找到的以下目錄到我的c#程序中。我應該如何繼續?我應該使用Impersonate方法嗎?使用c從另一個域訪問遠程目錄#

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

請幫忙。

回答

0

在這之前,你需要以編程方式(如果這是你想要解決的問題)用適當的用戶創建一個到域的連接。你可以使用這個類做:

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方法將正常工作。這可能會留下一個開放的連接(但它不會創建多個連接),但無論如何,您可能想要創建代碼來關閉它,正確處理所有事情,等等。這僅僅是一個起點。

+0

我應該在哪裏創建此連接? – velvt

+0

@velvt在調用該方法之前 – Gaspa79

相關問題