You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在扩展程序中查找用户/工作区/文件夹级别的设置文件路径?

获取VS Code不同作用域的设置文件位置

完全可以在VS Code扩展中获取User、Workspace、Folder三个作用域下的设置文件位置,以下是具体实现方式:

User 作用域

User级别的设置文件路径因操作系统而异,通过VS Code提供的API可以准确获取其本地绝对路径:

import * as vscode from 'vscode';

function getUserSettingsPath(): string | undefined {
    const configInspect = vscode.workspace.getConfiguration().inspect('');
    return configInspect?.userUri?.fsPath;
}

如果用户从未修改过User级别的设置,返回值可能为undefined,否则会返回类似Windows下%APPDATA%\Code\User\settings.json的路径。

Workspace 作用域

Workspace作用域分两种场景,API会自动适配:

  • 单一文件夹工作区:返回该文件夹下.vscode/settings.json的路径
  • 多根工作区:返回对应的.code-workspace文件路径

实现代码:

function getWorkspaceSettingsPath(): string | undefined {
    const configInspect = vscode.workspace.getConfiguration().inspect('');
    return configInspect?.workspaceUri?.fsPath;
}

Folder 作用域(多根工作区中的单个文件夹)

在多根工作区中,每个独立文件夹可拥有专属设置文件,需指定目标文件夹来获取:

function getFolderSettingsPath(folder: vscode.WorkspaceFolder): string | undefined {
    const configInspect = vscode.workspace.getConfiguration('', folder).inspect('');
    return configInspect?.workspaceFolderUri?.fsPath;
}

// 遍历所有工作区文件夹,批量获取各自的设置文件路径
vscode.workspace.workspaceFolders?.forEach(folder => {
    const path = getFolderSettingsPath(folder);
    if (path) {
        console.log(`Folder ${folder.name} settings path: ${path}`);
    }
});

每个文件夹的设置文件默认存放在其根目录下的.vscode/settings.json,只有当该文件夹存在自定义设置时,才会返回有效路径。

注意事项

  • 所有方法返回的都是本地文件系统的绝对路径,可直接展示给用户。
  • 若某个作用域未做任何自定义设置(所有设置使用默认值),对应的URI会是undefined,需做好空值判断。

内容的提问来源于stack exchange,提问作者Sajith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 16:17:12