Amar
Amar

Reputation: 69

WebClient.Downloadfile API is not working in powershell

(new-object System.Net.WebClient).Downloadfile("https://www.dropbox.com/sh/tsyz48qg0rq3smz/QAstBLgPgN/version.txt", "C:\Users\Brangle\Desktop\version.txt") API download invalid data.

version.txt file need to download. But actually it is downloading some xml file contains in version.txt on destination location

Thanks in advance

Upvotes: 0

Views: 3337

Answers (3)

majkinetor
majkinetor

Reputation: 9056

Here is the function:

function download-dropbox($Url, $FilePath) {
    $wc = New-Object system.net.webclient
    $req = [System.Net.HttpWebRequest]::Create($Url)
    $req.CookieContainer  = New-Object System.Net.CookieContainer
    $res = $req.GetResponse()

    $cookies = $res.Cookies | % { $_.ToString()}
    $cookies = $cookies -join '; '

    $wc.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookies)
    $newurl = $url + '?dl=1'

    mkdir (Split-Path $FilePath) -force -ea 0 | out-null
    $wc.downloadFile($newurl, $tempFile)
}

Upvotes: 1

Raf
Raf

Reputation: 10117

Re: LogMeIn - theyuse a cookie base authentication so you can't use the previous code. Try this, it gets a cookie from the first response and then uses that to download using webclient:

$url = "https://secure.logmein.com/fileshare.asp?ticket=01_L5vwmOrmsS3mnxPO01f5FRbWUwVKlfheJ5HsfpTV"
$wc = New-Object system.net.webclient  
$req = [System.Net.HttpWebRequest]::Create($url)  
$req.CookieContainer  = New-Object System.Net.CookieContainer  
$res = $req.GetResponse()
$cookie = $res.Cookies.Name + "=" + $res.Cookies.Value
$wc.Headers.Add([System.Net.HttpRequestHeader]::Cookie, $cookie)  
$newurl = $url + "`&download=1"
$wc.downloadFile($newurl, "c:\temp\temp.zip")

Upvotes: 0

Raf
Raf

Reputation: 10117

You are trying to download the dropbox page which presents your file in a nice dropbox-themed html. You need to extract the real url and can do so using the following code:

$wc = New-Object system.net.webclient;
$s = $wc.downloadString("https://www.dropbox.com/sh/tsyz48qg0rq3smz/QAstBLgPgN/version.txt");
$r = [regex]::matches($s, "https://.*token_hash.*(?=`")");
$realURL = $r[$r.count-1].Value;
$wc.Downloadfile($realURL, "U:\version.txt");

The regex part looks for a url starting https://, has a string token_hash in the middle and ends one character before double quotes character ". The line in question is:

FilePreview.init_text("https://dl.dropboxusercontent.com/sh/tsyz48qg0rq3smz/QAstBLgPgN/version.txt?token_hash=AAEGxMpsE-T4xodBPd3A6uPTCr0uqh7h4B2YUSmTDJHmjg", 0, null, 0)

Hope this helps.

Upvotes: 1

Related Questions