#DevHack: How to rename a file from a VSCode extension

August 16, 2021

Renaming a file is something that we do very often, but in my case, I wanted to do it from within a Visual Studio Code extension. When I first looked at the APIs and available documentation, I found the vscode.executeDocumentRenameProvider command and RenameProvider.

Info Documentation from this can be found here built-in commands.

Now, I thought, there must be an easier way, so I started to look around at the APIs available, and luckily there is an easy option.

On the vscode, its workspace namespace, you can access the fs or file system via: vscode.workspace.fs. The fs instance delivers you a couple of valuable methods you could use, like rename.

workspace.fs methods
workspace.fs methods

If you want to rename a file, you just need to use the rename method as follows:

1
2
3
4
5
6
const editor = vscode.window.activeTextEditor;
if (editor) {
  await vscode.workspace.fs.rename(editor.document.uri, vscode.Uri.file(newPath), {
    overwrite: false
  });
}

Comments

comments powered by Disqus