Search code examples
visual-studio-codevscode-extensions

How to get file name or path in vscode extension when user right click on file in explorer/context?


My extension creates a context menu in the explorer tree:

"contributes": {
        "commands": [
            ...
            {
                "command": "myextension.mycommand",
                "title": "Run my command"
            }
        ],
        "menus": {
            "explorer/context": [{
                "when": "resourceLangId == python",
                "command": "myextension.mycommand",
                "group": "MyGroup"
          }]
        }
    }

In extension.ts:

export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('myextension.mycommand', () => {
    //How to get the filename or file path here?
}));

I want to get the filename or file path of the file I've right click on the context menu when run my command. Can you tell me how? Thank you very much!


Solution

  • The callback will receive an argument with a vscode.Uri object:

    vscode.commands.registerCommand('myextension.mycommand', (uri:vscode.Uri) => {
        console.log(uri.fsPath);
    });