【问题标题】:Webclient.UploadFile() uploads file to destination, but throws an errorWebclient.UploadFile() 将文件上传到目的地,但抛出错误
【发布时间】:2021-12-05 15:53:55
【问题描述】:

所以我有这段代码可以在生成 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."
}

【问题讨论】:

  • 您能否在收到错误后运行以下命令并使用输出编辑您的帖子,请$Error[0].Exception.PSObject.Properties | select Name,Value | FL *。如果文件上传正常,我怀疑由于这一行而发生错误 - $resp = System.Text.Encoding.ASCII.GetString($rawResponse)

标签: .net powershell error-handling


【解决方案1】:

因为你的 2nd catch 块被击中,你知道它不是WebException

由于这条无效行,您的脚本应该会产生错误:

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

你可能想写的是:

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

另外,如果你改用它是最安全的,以确保你使用的是正确的编码:

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

【讨论】:

  • 它来自这个我用``` $resp = $wc.Encoding.GetString($rawResponse) ```试了一下,它没有错误。
猜你喜欢
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多