Use C# CSOM ClientContext to download file from SharePoint document library or OneDrive for Business

This post will show how to download a file from any document library.

 

Using SharePoint SDK in Windows Phone 8 and the ISF (Isolated File Storage):

The steps:

  1. Get the relative url of the file
  2. Use the ClientContext object to download the file to the ISF
  3. Open the file in the phones office apps

The code:

Assuming you have the Item object:

string fileRef =

Stream inputStream;

private void BMSStackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)

{

loadingProgressBar.IsVisible = true;

//get the relative url of the file

string fileRef = item[“FileRef”].ToString();

//get just the filename part

string fileName = fileRef.Substring(fileRef.LastIndexOf(“/”)+1);

 

Microsoft.SharePoint.Client.File.OpenBinaryDirect(Context, fileRef,

(object eventSender, OpenBinarySucceededEventArgs eventArgs) =>

{

if (eventArgs.Stream != null)

inputStream = eventArgs.Stream; //instantiating stream using the sharepoint file stream

Deployment.Current.Dispatcher.BeginInvoke(() =>

{

using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())

{

//create a local file with the same name using the input stream and saving through the output stream

using (IsolatedStorageFileStream outputStream = ISF.CreateFile(fileName))

{

try

{

byte[] bytes = new byte[inputStream.Length];

inputStream.Read(bytes, 0, (int)inputStream.Length);

outputStream.Write(bytes, 0, bytes.Length);

outputStream.Flush();

 

}

catch (Exception ex2)

{

}

}

loadingProgressBar.IsVisible = false;

LaunchFile(fileName);

 

 

}

});

}, null); //im passing null for the failed event. this should be handled properly though

}

private async void LaunchFile(string fileName)

{

var file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);

await Windows.System.Launcher.LaunchFileAsync(file);

}

 

 

Using Client OM in C#:

Assuming you have the Item object:

//get the URL of the file you want:

var fileRef = item[“FileRef”];

//get the file contents:

FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());

using (var memory = new MemoryStream()) {

byte[] buffer = new byte[1024 * 64];

int nread = 0;

while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0) {

memory.Write(buffer, 0, nread);

}

memory.Seek(0, SeekOrigin.Begin);

// … here you have the contents of your file in memory,

// do whatever you want

}

 

In JavaScript:

  1. Globally declare the content and web objects as shown below.

    var context = SP.ClientContext.get_current(); //gets the current context

  2. var web = context.get_web(); //gets the web object

Now write the function to read a file in a Document Library.
function readFile() {

context.load(web);

context.executeQueryAsync(OnreadServerRelativeURL, readFileFailure);

}

function OnreadServerRelativeURL() {

var fileUrl = web.get_serverRelativeUrl() + “/MyLibrary/MyTextFile.txt”;

$.ajax({

url: fileUrl,

type: “GET”

})

.done(Function.createDelegate(this, readFileSuccess))

.error(Function.createDelegate(this, readFileFailure));

}

function readFileSuccess(data) {

//do whatever you need to with the data

alert(data);

}

function readFileFailure(sender, args) {

debugger;

alert(‘Failed to read a file. Error:’ + args.get_message());

}