简体   繁体   中英

Access a file from a SharePoint site

My requirement is to access a Excel file located in a SharePoint Team site using C#. I can upload and download files directly from the site, I have given permission for that. But the site is maintained by some other group, which no service is exposed. Is there any approach to access the file using C#.

When you don't have direct access to the SharePoint system itself, you should still be able to use the REST Service API of SharePoint, as long as your colleagues didn't deactivate the responsible service application.

You can find the documentation for reading files by using REST and SharePoint 2013 here .

For accessing REST via C# you use code like this:

HttpWebRequest endpointRequest =
  (HttpWebRequest)HttpWebRequest.Create(
  "http://<site url>/_api/web/getfilebyserverrelativeurl('/Shared Documents/filename.docx')");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
endpointRequest.Headers.Add("Authorization", 
  "Bearer " + accessToken);
HttpWebResponse endpointResponse =
  (HttpWebResponse)endpointRequest.GetResponse();

There are several ways of downloading a file from SharePoint, you could utilize specific SharePoint APIs like CSOM for that purpose or vanilla .NET capabilities (eg HttpClient Class , WebClient Class ) as demonstrated below:

using (var client = new WebClient())
{
    client.DownloadFile(sharePointFileUrl, localFileName);
}  

How to download a file using SharePoint CSOM API

SharePoint CSOM API contains File.OpenBinaryDirect method that is intended for downloading a file from SharePoint:

private static void DownloadFile(Web web, string fileUrl,string targetPath)
{
    var ctx = (ClientContext)web.Context;
    ctx.ExecuteQuery();
    using(var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileUrl))
    {
         var fileName = Path.Combine(targetPath, System.IO.Path.GetFileName(fileUrl));
         using (var fileStream = System.IO.File.Create(fileName))
         {
             fileInfo.Stream.CopyTo(fileStream);
         }
    }
}

Usage

using (var ctx = new ClientContext(webUri))
{
      DownloadFile(ctx.Web, "/documents/Report.xslx", @"c:\downloads");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM