12 May, 2014

Download file from OneDrive: Solved

I’m lost for words with the lack of documentation for using OneDrive from a Windows Phone 8.1 application. I has literally taken me days to get this one to work! Finally, a comment on a forum somewhere guided me in the right direction.

How do you download the content of a file found on your OneDrive? If you just use the poor samples at MS webpage, you gain the metadata of the file you are downloading. Not the content which is what you are after (or I was!).

Downloading a file (content!) from a OneDrive folder is done in the following way.

1) Establish a session with OneDrive

 public async Task<LiveConnectSession> Initialize()
LiveAuthClient auth = new LiveAuthClient();
var r = await auth.InitializeAsync(new string[] { "wl.skydrive_update"});
return r.Session;
2) Download the file (important is the “/content” as id)
   public async Task<IStorageFile> LoadFile(string fileId)
//temporary file for write
var fileTmp = await ApplicationData.Current.LocalFolder.CreateFileAsync("tmp.xml", CreationCollisionOption.ReplaceExisting);

var session = await Initialize();
var liveClient = new LiveConnectClient(session);

//add /content to get the content of the file instead of the metadata.
await liveClient.BackgroundDownloadAsync(fileId + "/content", fileTmp);

return fileTmp;

3) read the file content

   public async Task RestoreFile(IStorageFile file)
//read incoming file
using (var fs = await file.OpenStreamForReadAsync())
var vault = ConvertStreamToObject(new StreamReader(fs, System.Text.Encoding.UTF8, true));

var lst = vault.Entries.OrderBy(x => x.Title).ToList();

//save to disk
await SaveDataAsync(lst);
catch (Exception ex)

No comments: