401下载文件时出错-SharePoint ClientContext

本文关键字:-SharePoint ClientContext 出错 下载 文件 | 更新日期: 2023-09-27 18:19:39

对于下面的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);
                            }
                        }
                    }
                }

它给出这个错误的原因是什么?

401下载文件时出错-SharePoint ClientContext

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

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

我希望它能帮助你…:)

问题是,您需要以下内容,不要混合引用File的system.io,由于某种原因,编译器编译不好代码,并且要从这样的上下文调用,不要使用接口:

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