Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download a specific file from SharePoint (CSOM) using C#

I'm developing a C# based application that requires to download, checkout, upload, check in on a specific file from/to Sharepoint with CSOM. So I have two questions here:

Firstly, on download, is there others way to download a specific named file under folder "Document" instead of searching through GetItemByID(). Please refer to code below:

string siteUrl = @"http://test.com/sites/company/";

ClientContext ctx = new ClientContext(siteUrl);
ctx.Credentials = new NetworkCredential("username", "password" , "domain");            
ctx.AuthenticationMode = ClientAuthenticationMode.Default;

var list = ctx.Web.Lists.GetByTitle("Document");
var listItem = list.GetItemById();

ctx.Load(list);
ctx.Load(listItem, i => i.File);
ctx.ExecuteQuery();

var fileRef = listItem.File.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, fileRef);
var fileName = Path.Combine("C:\\", (string)listItem.File.Name);

using (var fileStream = System.IO.File.Create(fileName))
{
    fileInfo.Stream.CopyTo(fileStream);
}

Secondly, in regards to the workflow (download, modify, check out, upload, check in), is this feasible of doing?

Thanks in advance.

like image 214
johny Avatar asked Sep 12 '25 22:09

johny


1 Answers

For getting a specific file, you do not need to get the ListItem by Id. Instead, you can directly pass the server relative URL like this:

ClientContext clientContext = new ClientContext("http://sp/sites/dev");
Web web = clientContext.Web;

Microsoft.SharePoint.Client.File filetoDownload = 
    web.GetFileByServerRelativeUrl("/sites/dev/shared%20documents/mytest.txt");
clientContext.Load(filetoDownload);
clientContext.ExecuteQuery();

var fileRef  = filetoDownload.ServerRelativeUrl;
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(
                   clientContext, 
                   fileRef);
var fileName = Path.Combine("C:\\", (string)filetoDownload.Name);

using (var fileStream = System.IO.File.Create(fileName))
{
    fileInfo.Stream.CopyTo(fileStream);
}

For other usage, checkout,update,checkin, I would suggest you can still use CSOM, as there are buit-in functions support:

File methods

like image 77
Jerry Avatar answered Sep 14 '25 13:09

Jerry