下载文件时出现401错误 - SharePoint ClientContext

时间:2014-08-28 09:19:15

标签: c# sharepoint sharepoint-2013

以下CilentContext代码在客户端计算机中下载文档。当代码命中OpenBinaryDirect()方法时,我会收到未经授权的401错误。

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

出现此错误的原因是什么?

2 个答案:

答案 0 :(得分:0)

@ Shaamil ...... 它抛出401错误,因为您没有足够的权限来访问该文件。 您正在使用系统帐户创建SPSite对象,但不使用额外的权限。

使用服务器对象模型时,可以直接创建相应的SPWeb对象(存储文件的位置) 使用site.OpenWeb(“您网站的服务器相对网址”)。 并使用该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..
...
}

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

答案 1 :(得分:-2)

问题是你需要以下内容,不要混合system.io引用File,由于某种原因编译器编译错误,并从这样的上下文调用,不要使用界面:

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