繁体   English   中英

使用 System.Net.WebClient.DownloadFile 下载文件时显示已损坏

[英]File appears corrupted when it's downloaded with System.Net.WebClient.DownloadFile

我将一个文件上传到云,它给了我直接下载链接。

通过单击此链接下载它可以正常工作,但是当我尝试通过 Powershell 上的System.Net.WebClient.DownloadFile下载它时,它会下载文件,但是当我打开它时,它说文件已损坏且无法读取

那是代码:

$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile("https://xxxxxx.com/xxxxx/xxx.exe","C:\Users\user\Desktop\xxx.exe")

有什么解决办法吗?

奇怪,这个逻辑对我有用。

您可以尝试添加$WebClient.Dispose()吗?

或其他PowerShell下载方法如:

$uri = "https://xxxxxx.com/xxxxx/xxx.exe"
$path = "C:\Users\user\Desktop\xxx.exe"

Invoke-WebRequest -Uri $uri -OutFile $path

使用 PowerShell 下载文件的 3 种方法

<#
# 1. Invoke-WebRequest

The first and most obvious option is the Invoke-WebRequest cmdlet. It is built
into PowerShell and can be used in the following method:
#>

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
Invoke-WebRequest -Uri $url -OutFile $output
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

<#
2. System.Net.WebClient

A common .NET class used for downloading files is the System.Net.WebClient class.
#>

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
$wc = New-Object System.Net.WebClient
$wc.DownloadFile($url, $output)

# OR

(New-Object System.Net.WebClient).DownloadFile($url, $output)
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

<#
3. Start-BitsTransfer

If you haven't heard of BITS before, check this out. BITS is primarily designed
for asynchronous file downloads, but works perfectly fine synchronously too
(assuming you have BITS enabled).
#>

$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
Import-Module BitsTransfer
Start-BitsTransfer -Source $url -Destination $output

# Or

Start-BitsTransfer -Source $url -Destination $output -Asynchronous
Write-Output "Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"

这是我个人每天使用的,来自通过我的个人资料导入的个人模块中的 function。

$webclient = New-Object System.Net.WebClient
$url       = 'https://download.microsoft.com/download/B/A/4/BA4A7E71-2906-4B2D-A0E1-80CF16844F5F/dotNetFx45_Full_setup.exe'

$filename = [System.IO.Path]::GetFileName($url)
$file     = "$TechToolsUNC\$filename"

$webclient.DownloadFile($url,$file)
Start-Process $file -Wait

我推测他与 powershell 无关,而是您的机器或网络上的其他因素,很可能是防病毒代理等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM