2014-08-28 104 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);