Webclient.UploadFile() 上传文件到目的地,但抛出错误
Webclient.UploadFile() uploads file to destination, but throws an error
所以我有这段代码可以在生成 xml 后将文件上传到目的地。检查服务器时,我发现该文件的内容正确,但从我的一个 catch 块中,我得到“发生无法解决的错误”。我不知道这是否是严重错误,因为我不知道错误是什么。该文件至少已上传,但我想找出此错误以便我可以解决它。有没有办法知道这里抛出了什么错误?
try {
$wc = New-Object System.Net.WebClient
$rawResponse = $wc.UploadFile("someURIhere", "Post", $File)
$resp = System.Text.Encoding.ASCII.GetString($rawResponse)
Write-Host $resp
}
catch [System.Net.WebException] {
$Request = $_.Exception
Write-host "Exception caught: $Request"
$crapMessage = ($_.Exception.Message).ToString().Trim()
Write-Output $crapMessage
}
catch {
Write-Host "An error occurred that could not be resolved."
}
因为您的 2nd 捕获块被命中,您知道它 不是 而是 WebException
。
您的脚本应该由于以下无效行而产生错误:
$resp = System.Text.Encoding.ASCII.GetString($rawResponse)
您可能想写的是:
$resp = [System.Text.Encoding]::ASCII.GetString($rawResponse)
此外,如果您改为使用此方式,则最安全,以确保您使用的是正确的编码:
$resp = $wc.Encoding.GetString($rawResponse)
所以我有这段代码可以在生成 xml 后将文件上传到目的地。检查服务器时,我发现该文件的内容正确,但从我的一个 catch 块中,我得到“发生无法解决的错误”。我不知道这是否是严重错误,因为我不知道错误是什么。该文件至少已上传,但我想找出此错误以便我可以解决它。有没有办法知道这里抛出了什么错误?
try {
$wc = New-Object System.Net.WebClient
$rawResponse = $wc.UploadFile("someURIhere", "Post", $File)
$resp = System.Text.Encoding.ASCII.GetString($rawResponse)
Write-Host $resp
}
catch [System.Net.WebException] {
$Request = $_.Exception
Write-host "Exception caught: $Request"
$crapMessage = ($_.Exception.Message).ToString().Trim()
Write-Output $crapMessage
}
catch {
Write-Host "An error occurred that could not be resolved."
}
因为您的 2nd 捕获块被命中,您知道它 不是 而是 WebException
。
您的脚本应该由于以下无效行而产生错误:
$resp = System.Text.Encoding.ASCII.GetString($rawResponse)
您可能想写的是:
$resp = [System.Text.Encoding]::ASCII.GetString($rawResponse)
此外,如果您改为使用此方式,则最安全,以确保您使用的是正确的编码:
$resp = $wc.Encoding.GetString($rawResponse)