简体   繁体   中英

How to get project folder path in visual studio code extension

I am trying to get project folder path in visual studio code extension but very difficult to find the answer. My code is not working. I do not know it is possible or not. I have checked in google no one answer for this question. Anyone know about this please help me to find the answer.

在此处输入图像描述

extension.js:

var vscode = require("vscode");
var path = require("path");

exports.activate = context => {
const findPath = 
vscode.commands.registerCommand('extension.search', () => {

   let findprojectfolderPath = vscode.workspace.uri.fsPath; // Not working

   console.log(findprojectfolderPath);

});
}

If you open the folder, then you can get the workspace variable.

let folderName = vscode.workspace.name; // get the open folder name
let folderPath = vscode.workspace.rootPath; // get the open folder path

I would like to update Pushprajsinh Chudasama's answer as vscode.workspace.rootPath is now deprecated . It is being replaced by vscode.workspace.workspaceFolders which returns an array of WorkspaceFolders | undefined WorkspaceFolders | undefined . To retrieve the path to all your workspace folders, you may now use:

vscode.workspace.workspaceFolders?.map(folder => folder.uri.path)

If you want to find the path of the file currently is opened by the user, then you need this

console.log(vscode.window.activeTextEditor.document.uri.fsPath);

Read this documentation for information further: https://code.visualstudio.com/api/references/vscode-api#TextDocument

As It turned out vscode.workspace.rootPath is deprecated and the only solution that I found so far is described in this answer

VS Code extension - get full path

This function gets the workspace directory for the file currently open. If there is no active editor or the file doesn't belong to a workspace, it returns undefined .

import * as vscode from "vscode";

function getDocumentWorkspaceFolder(): string | undefined {
  const fileName = vscode.window.activeTextEditor?.document.fileName;
  return vscode.workspace.workspaceFolders
    ?.map((folder) => folder.uri.fsPath)
    .filter((fsPath) => fileName?.startsWith(fsPath))[0];
}

You must change the code. Like the example below.

vscode.commands.registerCommand('extension.search', (p: { fsPath: string }) => {

   // p is an object whose path is fsPath.

   console.log(p.fsPath);

});

Maybe this link can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM