4

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.

johny
  • 65
  • 1
  • 1
  • 5

1 Answers1

4

For getting specific file, no need to get ListItem by Id, instead, directly pass server relativer 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

Jerry
  • 3,480
  • 1
  • 10
  • 12