在.NET应用程序中将文件保存在OneDrive中

时间:2017-07-26 01:40:50

标签: c# .net office365 onedrive

我正在.NET中执行C#个应用程序,除了其他功能外,用户还可以登录到他们的OneDrive帐户并将文件保存到他们的帐户。我从Windows Desktop (.NET) guided setup下载了代码,该代码教导注册应用程序并对用户进行身份验证,并且该部分按照建议运行。但是,我需要知道如何将部件放到save the file in the accountOnedrive的根文件夹(用户只会登录帐户,然后输入要保存在帐户中的文件,它将保存在根文件夹中)。我在GitHub中看到了一些示例,但是所有这些示例都适用于Web应用程序。

更新

using Microsoft.Identity.Client;

public partial class App : Application
{
    private static string ClientId = "your_client_id_here";

    public static PublicClientApplication PublicClientApp = new PublicClientApplication(ClientId);

}

public partial class MainWindow : Window
{
    string _graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";

    string[] _scopes = new string[] { "user.read" };

    public MainWindow()
    {
        InitializeComponent();
    }

    private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
    {
        AuthenticationResult authResult = null;

        try
        {
            if (authResult == null)
            {
                authResult = await App.PublicClientApp.AcquireTokenSilentAsync(_scopes, App.PublicClientApp.Users.FirstOrDefault());
            }
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                authResult = await App.PublicClientApp.AcquireTokenAsync(_scopes);
            }
            catch (MsalException msalex)
            {
                ResultText.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
            }
        }
        catch (Exception ex)
        {
            ResultText.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
            return;
        }

        if (authResult != null)
        {
            ResultText.Text = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);
            DisplayBasicTokenInfo(authResult);
            this.SignOutButton.Visibility = Visibility.Visible;
        }
    }
}

public async Task<string> GetHttpContentWithToken(string url, string token)
{
    var httpClient = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response;
    try
    {
        var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
        //Add the token in Authorization header
        request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
        response = await httpClient.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
    catch (Exception ex)
    {
        return ex.ToString();
    }
}

参考: Windows桌面(.NET)指导设置

0 个答案:

没有答案