无需用户登录即可从SharePoint文档库下载

时间:2016-03-21 13:21:20

标签: c# asp.net sharepoint

我正在尝试从ASP.NET应用程序从Sharepoint文档库下载文件。我能够得到一个文件列表,但是当我使用相同的上下文下载时,我得到了一个(401)Unauthorized错误。问题类似于this question,但由于我试图在没有用户登录的情况下下载文件,因此没有用户名和密码。 我的代码如下:

using (var ctx = TokenHelper.GetClientContextWithAccessToken(ConfigurationManager.AppSettings("url"), TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken) )
{                
    var web = ctx.Web;

    Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(fromLocation);

    ctx.Load(file);

    ctx.ExecuteQuery();

    var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, file.ServerRelativeUrl);
    using (var ms = new MemoryStream())
    {
        fileInfo.Stream.CopyTo(ms);
        return ms.ToArray();
    }
}

2 个答案:

答案 0 :(得分:0)

似乎您正在使用提供商托管应用程序,如果是,您是否设置了应用程序权限以从指定的文档库中读取?

您还可以检查ULS日志并搜索401文本,以查看尝试下载文档的标识有什么问题

答案 1 :(得分:0)

从文件中获取流。我能够将其转换为字节数组并在其上调用二进制写入,而无需使用OpenBinaryDirect并处理身份验证问题

using (var ctx = TokenHelper.GetClientContextWithAccessToken(ConfigurationManager.AppSettings("url"), TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken) )
{                
    var web = ctx.Web;

    Microsoft.SharePoint.Client.File file = web.GetFileByServerRelativeUrl(fromLocation);
    ClientResult(Of Stream) data = file.OpenBinaryStream();

    ctx.Load(file);
    ctx.ExecuteQuery();


    HttpContext.Current.Response.ContentType = MimeMapping.GetMimeMapping(file.Name);
    HttpContext.Current.Response.AppendHeader("content-disposition", "inline;filename=" + file.Name);
    HttpContext.Current.Response.AppendHeader("content-length", data.Value.Length.ToString());
    HttpContext.Current.Response.BinaryWrite(StreamToByteArray(data.Value));
    HttpContext.Current.Response.Flush();
}


private byte[] StreamToByteArray(ByVal input As Stream)
{
    byte[] buffer = new byte[16 * 1024];

    using (MemoryStream ms = new MemoryStream())
    { 
        int read; 
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        { 
            ms.Write(buffer, 0, read);
        } 
        return ms.ToArray();
    } 
}

我遇到的一个问题是大文件。使用OpenBinaryStream而不是OpenBinaryDirect意味着在下载开始之前加载文件需要一段时间。

相关问题