HOW TO: Change file extension of an existing item in SharePoint document library

This post is a contribution from Aaron Miao, an engineer with the SharePoint Developer Support team.

For various reasons, people want to change the file extension of an existing item in a document library.  For example, with SharePoint 2007, files with JSON extension in document library can be opened without problems.  However, once you upgrade to SharePoint 2010, you cannot open the file anymore.  You’ll get an error similar to what’s shown below.

An error occurred during the processing of /Shared Documents/test.json.

The page must have a <%@ webservice class=”MyNamespace.MyClass” … %> directive.

In order to be able to see the JSON file content with SharePoint UI, one option is to change the file extension from JSON to TXT.  But you cannot change the name or display name of the file.  This can be accomplished by two methods as shown in the below samples that uses PowerShell.  And of course, you can do the same with SharePoint server OM.

Use SPFile.MoveTo

$site = Get-SPSite "http://yoursite"
$web  = $site.RootWeb
$list = $web.Lists["Shared Documents"]
$item = $list.GetItemById(0)
$file = $item.File
$file.MoveTo($item.ParentList.RootFolder.Url + "/” + ”test.txt")

Use SPFile.CopyTo

$site = Get-SPSite "http://yoursite"
$web  = $site.RootWeb
$list = $web.Lists["Shared Documents"]
$caml = '
      <FieldRef Name="File_x0020_Type" />
      <Value Type="Text">json</Value>
$query = new-object Microsoft.SharePoint.SPQuery
$query.Query = $caml
$items = $list.GetItems($query)
foreach($item in $items)
      $file = $item.File
      $url = $file.ServerRelativeUrl
      $newurl = $url.replace(".json", ".txt")

Hope this was helpful.

Comments (5)

  1. Anonymous says:

    Hi Cornelius,

    Both MoveTo() and CopyTo() keeps metadata (e.g Title, CustomCol). Yes, a new copied item from CopyTo() has no version history from source item.

  2. Hey Aaron,

    Good article.  My understanding is that SPFile.MoveTo() retains version history and metadata of the item which .CopyTo() creates a new copy that hence has no version history.

    Could you confirm that please?

  3. SharePoint 2013 Developer Certification Training says:

    Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.">SharePoint 2013 Developer Certification Training Online

  4. Chunkyfeather says:

    Hi – I had the same issue using SharePoint 2013, we just renamed the file extensions, by opening the document library in explorer view. Set the explorer view to "show extensions" and then renamed the extension.

    Worked for our needs very well, plus in my opinion less risky than using code.

  5. JoeD says:

    I don’t think you need to call Update() after MoveTo(). I get an error when I do. If I remove it and only call MoveTo(), it works fine for me.

Skip to main content