Search code examples
sharepointpowershellsharepoint-2010

Powershell: WriteErrorException on upload of file to SharePoint using System.Net.WebClient.UploadFile


I'm trying to upload a file from local to SharePoint using below piece of code. But somehow this error message is thrown which leaves me wondering about the cause:

Exception calling "UploadFile" with "3" argument(s): 
"An exception occurred during a WebClient request."
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId :              Microsoft.PowerShell.Commands.WriteErrorException,CopyFileToSharePoint.ps1

Anybody any ideas?

  • The user running the script has permissions to upload a file, e.g. using IE interactively.
  • And no, this is a remote server, thus I cannot use Microsoft.SharePoint classes.

The code

#Copy the file to the destination on SharePoint using WebClient
$SourceFile = $SourcePath + "\" + $FileName
$DestinationFile = $DestinationPath + "/" + $FileName

$client = new-object System.Net.WebClient
$client.UseDefaultCredentials=$true

if ( -not (Test-Path $DestinationPath) ) {
New-Item $DestinationPath -Type Directory  | Out-Null
}

$result |% {
Write-Host "Uploading $SourceFile to $DestinationFile"

try{
    $client.UploadFile($SourceFile, $DestinationFile)
}
catch{
    #one simple retry...
    try{
        $client.UploadFile($SourceFile, $DestinationFile)
    }
    catch{
        write-error "Failed to upload $SourceFile, $_"
    }
}
}   

Solution

  • Solved! What finally seemed to work, was setting the contenttype:

    $client.ContentType = "application/octet-stream";
    

    That somehow resolved the issue. Got the idea to try from this thread: Error using HttpWebRequest to upload files with PUT