Home > Net >  Webclient.UploadFile() uploads file to destination, but throws an error
Webclient.UploadFile() uploads file to destination, but throws an error

Time:10-19

So I have this code to upload a file to the destination after the xml is generated. Checking the server I see that the file is there with the correct contents, but from one of my catch blocks I get the "An error occurred that could not be resolved." I cannot tell if this is a critical error because I do not know what the error is. The file is at least uploaded, but I would like to figure out this error so I can resolve it. Is there a way to know what error is being thrown here?

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."
}

CodePudding user response:

Because your 2nd catch block is hit, you know it's not an WebException.

Your script should produce an error because of this invalid line:

$resp = System.Text.Encoding.ASCII.GetString($rawResponse)

What you probably wanted to write is:

$resp = [System.Text.Encoding]::ASCII.GetString($rawResponse)

Also, you're safest if you use this instead, to make sure you're using the right encoding:

$resp = $wc.Encoding.GetString($rawResponse)
  • Related