📜 ⬆️ ⬇️

How to easily work with OneDrive from UWP apps


I continue to talk about interesting / useful things from the XAML / C # world of UWP applications. OneDrive API is part of Microsoft Graph . To work with OneDrive, you can use the OneDrive REST API, which uses the HTTP protocol and in particular its methods GET, POST, DELETE, PUT ...

In addition, in accordance with the new principles of Microsoft, the OneDrive SDK for CSharp wrapper library was created, which facilitates the work and use of the service from the code of your applications.

OneDrive SDK for CSharp is a Portable Class Library (PCL) which is intended for the following types of projects:

.NET 4.5.1
.NET for Windows Store apps
Windows Phone 8.1 and higher
')
To install the SDK, you can run the command in the NuGet Package Manager Console

Install-Package Microsoft.OneDriveSDK 

or in VS manager NuGet use the search phrase Microsoft.OneDriveSDK

After creating a universal application, you must associate it with the Windows store. Thus, it will automatically be registered in the Live SDK application group. At https://apps.dev.microsoft.com/#/appList, you can verify that the application is registered in the Live SDK applications group. As I understand it, all Windows Store apps by default fall into this group.

Authentication occurs with a few lines of code:

  string[] scopes = { "wl.signin", "onedrive.readwrite" }; IOneDriveClient _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes); await _client.AuthenticateAsync(); 

All rights / permissions (scopes) are available at the link: Authentication scopes

During authentication, a new window opens in which the user can enter his or her data:



You can exit using the following code:

 await _client.SignOutAsync(); 

I will give the most typical operations with files. You can download the file using this snippet:

  string[] scopes = { "wl.signin", "onedrive.readwrite" }; IOneDriveClient _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes); AccountSession session = await _client.AuthenticateAsync(); if (!_client.IsAuthenticated) return; Item item = await _client .Drive .Root .ItemWithPath("CodeExamples/MyDemo.zip") .Request() .GetAsync(); using (Stream contentStream = await _client .Drive .Items[item.Id] .Content .Request() .GetAsync()) { StorageFile file = await ApplicationData.Current.LocalFolder. CreateFileAsync("MyDemo.zip", CreationCollisionOption.OpenIfExists); using (Stream outputstream = await file.OpenStreamForWriteAsync()) { await contentStream.CopyToAsync(outputstream); } } 

And download using this:

 string[] scopes = { "wl.signin", "onedrive.readwrite" }; IOneDriveClient _client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(scopes); AccountSession acse = await _client.AuthenticateAsync(); if (!_client.IsAuthenticated) return; FileOpenPicker fileOpenPicker = new FileOpenPicker(); fileOpenPicker.FileTypeFilter.Add(".jpg"); StorageFile file = await fileOpenPicker.PickSingleFileAsync(); if (file != null) { using (Stream contentStream = await file.OpenStreamForReadAsync()) { var uploadedItem = await _client .Drive .Root .ItemWithPath("CodeExamples/" + file.Name) .Content .Request() .PutAsync<Item>(contentStream); } } 

A description of other file operations is available via a link to GitHub: Items in the OneDrive SDK for C #

But in this way you can get a list of items in the root folder:

  IChildrenCollectionPage ic= await _client .Drive .Root .Children .Request() .GetAsync(); 

Now let's take a look at the same operation, but using the REST API. To do this, we need Access Token, which we can get from the object of the active session - AccountSession (we use the capabilities of the OneDrive SDK to simplify working with the REST API). And you also need the HttpClient class from the System.Net.Http space:

  Uri uri = new Uri("https://api.onedrive.com/v1.0/drive/root/children"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.AccessToken); string jsonstring = await client.GetStringAsync(uri); 

As a result, we get a string in the form of JSON listing all the items on OneDrive in the root folder.
You can not register the application in the Store, but get a temporary Access Token (valid for one hour) for experiments. To do this, on the OneDrive authentication and sign-in page, click the Get Token button.

The first method is obviously simpler and shorter, but the second one can also be useful. Let's say you can get a link to a file like this:

  Uri uri = new Uri("https://api.onedrive.com/v1.0/drive/root:/CodeExamples/MyDemo.zip:/action.createLink"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.AccessToken); var requestJson = JsonConvert.SerializeObject( new RequestLinkInfo { type = "view" }); var content = new StringContent(requestJson,Encoding.UTF8,"application/json"); var response = await client.PostAsync(uri,content); LinkResponseInfo result = JsonConvert.DeserializeObject<LinkResponseInfo>( await response.Content.ReadAsStringAsync()); 

Looking at the content, you may notice that in the Uri line the path to the file is framed by a colon. Alternatively, you can use the file id /drive/items/{item-id}/action.createLink .

To serialize and deserialize JSON, we need the following classes:

  public class RequestLinkInfo { public string type { get; set; } //  : view, edit  embed public string scope { get; set; } // optional -  : anonymous  organization } public class LinkResponseInfo { public string id { get; set; } public string[] roles { get; set; } public Link link { get; set; } } public class Link { public string type { get; set; } public string scope { get; set; } public string webUrl { get; set; } public OneDriveApplication application { get; set; } } public class OneDriveApplication { public string id { get; set; } public string displayName { get; set; } } 

The URL itself can be obtained from the result object:

  string fileurl = result.link.webUrl; 

What is interesting is that you can even use the old Live API and get access to information about the user who logged in:

  Uri uri = new Uri("https://apis.live.net/v5.0/me"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", session.AccessToken); string jsonstring = await client.GetStringAsync(uri); 

Although how long the Live API will still be available is difficult to say.
Official documentation is available here: Develop with the OneDrive API

Source: https://habr.com/ru/post/307130/


All Articles