Rename a file with webClient (or other)

Jay 21 Reputation points
2020-11-15T20:18:10.587+00:00

I am downloading a file from a SharePoint document library to the file system using $webclient.DownloadFile($ServerFileLocation,$DownloadPath)
Once downloaded I would like to rename the file in SharePoint. I see no such method in webClient and wondered what the best way to go is?

SharePoint Server Management
SharePoint Server Management
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Management: The act or process of organizing, handling, directing or controlling something.
2,795 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,355 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Sharath Kumar Aluri 3,071 Reputation points
    2020-11-15T23:42:07.36+00:00

    try with the below client code:

    string filename = "YourFileName.extension";
    Response.AppendHeader("Content-Disposition","attachment; filename="+ filename  +"");
    

    https://www.codeproject.com/Questions/508368/Topluschangeplusfileplusnameplusafterplusdownloadi

    Thanks & Regards,


  2. Sharath Kumar Aluri 3,071 Reputation points
    2020-11-16T01:37:53.067+00:00

    Gotcha, So you want to download files from the library to local system and then rename the files in a Library.

    Below script will download all files from library to your local system:

    #Config Variables
    $SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
    $FileRelativeURL = "/sites/Marketing/Shared Documents/Discloser Asia.docx"
    $DownloadPath ="C:\Temp"
    
    #Get Credentials to connect
    $Cred = Get-Credential
    
    Try {
        #Connect to PNP Online
        Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    
        #powershell download file from sharepoint online
        Get-PnPFile -Url $FileRelativeURL -Path $DownloadPath -AsFile
    }
    catch {
        write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
    }
    

    This below script will rename all files from Library.

    #Config Variables
    $SiteURL = "https://crescent.sharepoint.com/sites/marketing"
    $LibraryName = "Documents"
    
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
    
    #Get All Files from the document library
    $Files = Get-PnPListItem -List $LibraryName -PageSize 1000 | Where {$_["FileLeafRef"] -like "*.*"}
    
    #Loop through each File
    Write-host -f Green "Number of Files Found:"$Files.Count
    ForEach($File in $Files)
    { 
        Write-Host ("Renaming File '{0}' at {1}" -f $File["FileLeafRef"], $File["FileRef"])
        #Rename File
        Rename-PnPFile -ServerRelativeUrl $File["FileRef"] -TargetFileName "Old_$($File['FileLeafRef'])" -OverwriteIfAlreadyExists -Force
    }
    

    Reference:
    https://www.sharepointdiary.com/2016/09/sharepoint-online-download-file-from-library-using-powershell.html
    https://www.sharepointdiary.com/2017/10/sharepoint-online-rename-files-in-document-library-using-powershell.html

    Thanks & Regards,

    0 comments No comments

  3. Amos Wu-MSFT 4,051 Reputation points
    2020-11-16T07:44:43.783+00:00

    If you could accept not to use WebClient, you can use PowerShell CSOM to download the file and rename the file in one method.

    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"  
    Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  
       
    Function DownloadAndRename-FileFromLibrary()  
    {   
        param  
        (  
            [Parameter(Mandatory=$true)] [string] $SiteURL,  
            [Parameter(Mandatory=$true)] [string] $SourceFile,  
            [Parameter(Mandatory=$true)] [string] $TargetFile,  
            [Parameter(Mandatory=$true)] [string] $NewFileUrl  
        )  
       
        Try {  
            #Setup Credentials to connect  
            $username = "amos@contoso.onmicrosoft.com"  
            $password = "password"  
            $Cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)  
            $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)  
            #if you are using SharePoint On premise,just delete the above Credentials script  
            #Setup the context  
            $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  
            $Ctx.Credentials = $Credentials  
    
            $FileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($Ctx,$SourceFile)  
            $WriteStream = [System.IO.File]::Open($TargetFile,[System.IO.FileMode]::Create)  
            $FileInfo.Stream.CopyTo($WriteStream)  
            $WriteStream.Close()       
            Write-host -f Green "File '$SourceFile' Downloaded to '$TargetFile' Successfully!" $_.Exception.Message  
            $File = $Ctx.Web.GetFileByServerRelativeUrl($SourceFile)  
            $File.MoveTo($NewFileURL, [Microsoft.SharePoint.Client.MoveOperations]::Overwrite)  
            $Ctx.ExecuteQuery()       
            write-host -f Green "File Renamed successfully!"  
      }  
        Catch {  
            write-host -f Red "Error Downloading File!" $_.Exception.Message  
        }  
    }  
       
    #Set parameter values  
    $SiteURL="https://contoso.sharepoint.com/sites/dev/"  
    $SourceFile="/sites/dev/Shared Documents/1.pdf"  #Relative URL   
    $TargetFile="C:\Temp\1.pdf"  
    $NewFileURL="/sites/dev/Shared Documents/2.pdf"  
    #Call the function to download file   
    DownloadAndRename-FileFromLibrary -SiteURL $SiteURL -SourceFile $SourceFile -TargetFile $TargetFile -NewFileUrl $NewFileURL  
    

    Reference:
    https://www.sharepointdiary.com/2016/09/sharepoint-online-download-file-from-library-using-powershell.html
    https://www.sharepointdiary.com/2017/10/sharepoint-online-rename-files-in-document-library-using-powershell.html
    PNP powershell suggested by sharatha is also another solution.
    PNP powershell installation


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.