Reputation: 31
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 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, $_"
}
}
}
Upvotes: 2
Views: 6268
Reputation: 83
Also, the file you uploading should be 'Checked Out' in the SharePoint Library before run the UploadFile command. If not, UploadFile throws the above MethodException error of 3 arguments. I recreated this error manually toggling the SharePoint Library settings 'Allow Documents to be checked out before editing?'. But I don't know if we can do the check out/in using System.Net.WebClient programatically. (Din't find anything in the Documentation though)
Upvotes: 1
Reputation: 31
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
Upvotes: 1