2014-08-28 103 views
0

對於下面的CilentContext代碼來在客戶機中下載文檔。當代碼擊中OpenBinaryDirect()方法時,我得到未經授權的401錯誤。下載文件時出現401錯誤 - SharePoint ClientContext

using (SPSite site = new SPSite(SPContext.Current.Web.Url, SPUserToken.SystemAccount)) 
       { 
        using (FileInformation sharePointFile = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, serverRelativeUrlOfFile)) 
        { 
         using (Stream destFile = System.IO.File.OpenWrite(fileDestinationPath)) 
         { 
          byte[] buffer = new byte[8 * 1024]; 
          int byteReadInLastRead; 
          while ((byteReadInLastRead = sharePointFile.Stream.Read(buffer, 0, buffer.Length)) > 0) 
          { 
           destFile.Write(buffer, 0, byteReadInLastRead); 
          } 
         } 
        } 
       } 

爲什麼會出現此錯誤的任何原因?

回答

0

@ Shaamil ... 由於您沒有足夠的權限來訪問該文件,所以會拋出401錯誤。 您正在使用系統帳戶創建SPSite對象,但未使用額外權限。

當您使用服務器對象模型時,您可以通過使用site.OpenWeb(「您網站的服務器相對URL」)直接創建相應的SPWeb對象(存儲文件的位置) 。 並使用該SPWeb對象來獲取該文件。

由於您使用的是系統帳戶,因此您不會有任何身份驗證問題。 在下面的情況下,只有SPFile對象將使用系統帳戶權限進行訪問。

using (SPSite site = new SPSite("site url",SPUserToken.SystemAccount)) 
{ 
      using (SPWeb web = site.OpenWeb()) 
      { 
       SPFile file = (SPFile)web.GetFileOrFolderObject("file_url"); 
       using (Stream srcFile = file.OpenBinaryStream()) 
       { 
        using (Stream destFile = System.IO.File.OpenWrite("C:\\filename.extension")) 
        { 
         byte[] buffer = new byte[8 * 1024]; 
         int byteReadInLastRead; 
         while ((byteReadInLastRead = srcFile.Read(buffer, 0, buffer.Length)) > 0) 
         { 
          destFile.Write(buffer, 0, byteReadInLastRead); 
         } 
        } 
       } 
      } 
     } 

如果你想使用客戶端對象模型,如下使用... 如果你知道主人的憑據它只能(或者誰有權訪問該文件的用戶)級用戶。 如果您知道任何網站集管理員的憑據,那是最終的憑據。

System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("username","password","domain"); 
clientContext.Credentials = credentials; 

然後通過這個clientContext對象,如下得到FileInformation對象

using(FileInformation sharePointFile = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, serverRelativeUrlOfFile)) 
{ 
... 
// Do your operation as it is.. 
... 
} 

我希望它可以幫助你... :)

-2

的問題是,你需要以下,不't混合system.io引用文件,出於某種原因編譯器不良編譯代碼,並從這樣的上下文調用,不使用接口:

Microsoft.SharePoint.Client.File 
File file = context.Web.GetFileByServerRelativeUrl(fileRef);