我试图在Visual Studio代码扩展中获取项目文件夹路径,但很难找到答案。我的代码无法正常工作。我不知道有没有可能。我没有在google中找到这个问题的答案。任何人都知道这一点,请帮助我找到答案。
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);
});
}
答案 0 :(得分:1)
事实证明,vscode.workspace.rootPath
已被弃用,我目前找到的唯一解决方案在此答案中进行了描述
答案 1 :(得分:0)
如果打开文件夹,则可以获取workspace
变量。
let folderName = vscode.workspace.name; // get the open folder name
let folderPath = vscode.workspace.rootPath; // get the open folder path
答案 2 :(得分:0)
由于vscode.workspace.rootPath
已被弃用,我想更新Pushprajsinh Chudasama的答案。它被vscode.workspace.workspaceFolders
替换,该数组返回WorkspaceFolders | undefined
的数组。要检索所有工作空间文件夹的路径,现在可以使用:
vscode.workspace.workspaceFolders?.map(folder => folder.uri.path)
答案 3 :(得分:0)
如果要查找用户当前打开的文件的路径,则需要此
console.log(vscode.window.activeTextEditor.document.uri.fsPath);
阅读此文档以获取更多信息:https://code.visualstudio.com/api/references/vscode-api#TextDocument
答案 4 :(得分:0)
此函数获取当前打开的文件的工作区目录。如果没有活动编辑器或文件不属于工作区,则返回 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];
}