Search code examples
c#downloadonedrive

How to transform a OneDrive download link to a direct link that does not prompt the user?


In my app, users can enter a URL pointing to a file to be downloaded. They might enter a OneDrive URL such as https://1drv.ms/u/s!AqyU3_Or8s5Bm3eKXA31Xg7DFYpm?e=p0vACS. A OneDrive URL like this is fine when downloading via a web browser. You get a page with a download button saying "Hmm... looks like this file doesn't have a preview" -- which it doesn't in many cases, and you just click on the button.

The problem comes in my app, when I attempt to download the URL in the normal way, because the page with the download button is interposed.

I've been looking high and low for a way to transform a URL of this form to one which can be downloaded directly, without an interposing page (such as can be done for Google Drive).

What would that transformation be? Adding "?download=1" is mentioned in some places, but does not work for me.


Solution

  • I finally found the answer here:

    https://api.onedrive.com/v1.0/shares/u!XXXXX/root/content
    

    where XXXXX is the base 64 equivalent of the url.

    In C#:

    if ( url.StartsWith ( "https://1drv.ms/" ) )
    {
        url = "https://api.onedrive.com/v1.0/shares/u!" + url.ToBase64 () + "/root/content";
    }
    

    This works for OneDrive personal. I don't think it would work for OneDrive business or Sharepoint - see here

    It would be great if someone could post solutions for those here, if they exist.