How do I upload a file to OneDrive via the console app?

I am trying to upload a file to OneDrive from a console app. After digging around on Google, I found the Live SDK , but I couldn't find any article demonstrating how to download the file step by step using the Live SDK . Is there a good resource out there explaining how to do this? Thank.

+3


source to share


2 answers


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

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



Here is a snippet from the sample ApiExplorer 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


source


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

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

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

      

After that, create a WebBrowser element at runtime (you'll need a WinForms link for this).

Add the DocumentCompleted event to the WebBrowser and add your JavaScript to auto-fill the login form and simulate the login button, and within the same method, check if the WebBrowser URL is your ReturnUrl. If it is then parse authorization code and proceed to access and update the token.

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

      



Don't forget to put in some blocker code like:

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

      

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

After that, you can save these markers and use them later and update them periodically.

You may also need to throw JS exceptions.

By the way, one interesting thing with all their code samples is that they don't say that you don't need to specify the Client Secret if you are using your own (console) application.

0


source







All Articles