How to upload file to OneDrive through console app

2020-07-23 07:00发布

问题:

I am trying to upload a file to OneDrive from within console app. After digging a bit into Google I found Live SDK but I couldn't find any article demonstrating file upload step by step using Live SDK. Is there any good resource explaining how to it? Thanks.

回答1:

The LiveSDK has a number of examples and template code that are hosted on Github, https://github.com/liveservices/LiveSDK-for-Windows.

To see an example of how uploading is down you can explore the sample applications located at https://github.com/liveservices/LiveSDK-for-Windows/blob/master/src/Desktop/Samples/ApiExplorer/MainForm.cs#L259

Here is a snippet from the ApiExplorer example application:

OpenFileDialog dialog = new OpenFileDialog(); 
Stream stream = null; 
dialog.RestoreDirectory = true; 


if (dialog.ShowDialog() != DialogResult.OK) 
{ 
    throw new InvalidOperationException("No file is picked to upload."); 
} 
try 
{ 
    if ((stream = dialog.OpenFile()) == null) 
    { 
        throw new Exception("Unable to open the file selected to upload."); 
    }
    using (stream) 
    { 
        return await this.liveConnectClient.UploadAsync(path, dialog.SafeFileName, stream, OverwriteOption.DoNotOverwrite); 
    } 
} 
catch (Exception ex) 
{ 
    throw ex; 
}


回答2:

If you want to avoid user interaction completely, and still to use onedrive api in your console application you will have to implement custom logic.

First you need to mark your Main method as [STAThread] (single thread apartment module):

[STAThread]
static void Main(string[] args)     
{
 //...
}

After that create the WebBrowser control at runtime (you will need WinForms reference for that).

Add DocumentCompleted event to WebBrowser, and there inject your JavaScript in order to automatically fill login form and simulate login button click, and within the same method check if the WebBrowser url is your ReturnUrl. If it is then parse authorization code, and proceed to get access and refresh token.

setInterval(function(){
    //your code to interact with ui
}, 1000);

Don't forget to put some code blocker like:

while (!_autoLoginCompleted)
{
    Application.DoEvents();
    Thread.Sleep(100);
}

Navigate to https://login.microsoftonline.com/common/oauth2/authorize with appropriate parameters (clientId, returnUrl) to trigger DocumentCompleted event.

After that you can store these tokens and use them later, and periodically refresh them.

You might also need to suppress JS exceptions.

BTW, one interesting thing is with all their code samples that they are not saying that you don't need to specify Client Secret if you are using native (console) app.