Skip to content Skip to sidebar Skip to footer

Vs Code Extension - Get Full Path

I am writing a plugin for VS Code and I need to know the path of the file which is calling the extension, either if it was called from the editor context menu or explorer context m

Solution 1:

If you need the File use uri.fsPath If you need the Workspace Folder use uri.path

if(vscode.workspace.workspaceFolders !== undefined) {
    let wf = vscode.workspace.workspaceFolders[0].uri.path ;
    let f = vscode.workspace.workspaceFolders[0].uri.fsPath ; 

    message = `YOUR-EXTENSION: folder: ${wf} - ${f}` ;

    vscode.window.showInformationMessage(message);
} 
else {
    message = "YOUR-EXTENSION: Working folder not found, open a folder an try again" ;

    vscode.window.showErrorMessage(message);
}

More detail can get from VS Code API

Solution 2:

You can invoke the vscode window property to retrieve the file path or name depending on what you are looking for. This will give you the name of the file open in the current Tab when you execute the command. I don't know how it works if called from the explorer context.

var vscode = require("vscode");
var path = require("path");
functionactivate(context) {
   var currentlyOpenTabfilePath = vscode.window.activeTextEditor.document.fileName;
   var currentlyOpenTabfileName = path.basename(currentlyOpenTabfilePath);
   //...
}

Solution 3:

import * as vscode from"vscode";
import * as fs from"fs";   

var currentlyOpenTabfilePath = vscode.window.activeTextEditor?.document.uri.fsPath;

The above code is used to find the the path of file that is currently activated on vscode.

vscode.window.activeTextEditor gets editor's reference and document.uri.fsPath returns the path to that file in string format

Solution 4:

Here are examples of various paths returned by vscode in windows:

Extension path:

vscode.extensions.getExtension('extension.id').extensionUri.path
> /c:/Users/name/GitHub/extensionFolder 
vscode.extensions.getExtension('extension.id').extensionUri.fsPath
> c:\Users\name\GitHub\extensionFolder

Current folder:

vscode.workspace.workspaceFolders[0].uri.path
> /c:/Users/name/Documents/Notes 
vscode.workspace.workspaceFolders[0].uri.fsPath
> c:\Users\name\Documents\Notes

Current editor file:

vscode.window.activeTextEditor.document.uri.path
> /c:/Users/name/Documents/Notes/temp.md 
vscode.window.activeTextEditor.document.uri.fsPath
> c:\Users\name\Documents\Notes\temp.md

Note that path and fsPath refer to the same folder. fsPath provides the path in the form appropriate for the os.

Post a Comment for "Vs Code Extension - Get Full Path"