2012-12-17 24 views
2

我想從網絡上存在的文件夾讀取文件。使用asp.net代碼中的憑據從網絡位置讀取文件

當我嘗試手動訪問此文件夾(從運行命令給出一個像\\ ABCServer \ Documents這樣的路徑)它要求我輸入憑據(用戶名和密碼)。提供正確的憑據後,我可以訪問/讀取文件。

當我嘗試讀取從C#代碼中的相同文件ASP.NET它給了我一個錯誤:

Login Failure: unkown username or bad password

我怎麼能讀文件傳遞過程中通過C#代碼證書?

下面是代碼的一部分,我現在用:

Stream s = File.OpenRead(filePath); 
byte[] buffer = new byte[s.Length];    
try 
{ 
    s.Read(buffer, 0, (Int32)s.Length); 
}    
finally 
{ 
    s.Close(); 
}  

注:

  • 的代碼工作正常
  • 我使用ASP.NET 4.0的C#
  • IIS版本是7.5
+0

聽起來像你可能想看看使用模擬..如果是這樣籤的鏈接此計算器張貼http://platinumdogs.me/2008/10/30/net- c -impersonation-with-network-credentials/ – MethodMan

回答

4

這是http://support.microsoft.com/kb/306158

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); 

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(); 
} 
+0

LogonUserA(userName,domain,password,LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,ref token)!= 0 給我錯誤代碼'1326',當我手動輸入相同憑證時,精細。 – Ali

+0

我討厭這樣說,但它在我的機器上運行良好。你確定該域名是正確的嗎?我試着用好的密碼和壞的密碼,與好的工作,失敗與壞。 –

+0

感謝編輯weloytty,順便說一句,你曾經在美國在線工作,我似乎記得一個比爾Loytty(我認爲這是拼寫不同)當我在那裏 –

1

您可以這樣做使用模擬。 Here是如何完成的問題和答案。