【问题标题】:VS Code extension - get full pathVS Code 扩展 - 获取完整路径
【发布时间】:2017-01-26 22:56:12
【问题描述】:

我正在为 VS Code 编写一个插件,我需要知道调用扩展的文件的路径,无论是从编辑器上下文菜单或资源管理器上下文菜单中调用它,还是用户只需键入扩展命令。

function activate(context){
    // get full path of the file somehow
}

提前致谢!

【问题讨论】:

  • 所以你想知道扩展激活后当前活动的文件 - 只是想确保我正确理解了这个问题,因为这个要求有点不寻常;相反,人们通常想在运行特定命令时知道它。

标签: javascript typescript visual-studio-code vscode-extensions file-properties


【解决方案1】:

如果您需要文件,请使用uri.fsPath 如果您需要工作区文件夹,请使用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);
}

更多详情可咨询VS Code API

【讨论】:

  • rootPath 已弃用。我认为您可以使用以下方式获取路径: vscode.workspace.workspaceFolders[0].uri.fsPath
【解决方案2】:

您可以调用 vscode 窗口属性来检索文件路径或名称,具体取决于您要查找的内容。 当您执行命令时,这将为您提供在当前选项卡中打开的文件的名称。如果从资源管理器上下文中调用,我不知道它是如何工作的。

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

【讨论】:

  • 请注意fileName 用于新的无标题缓冲区只是没有标题,所以不要假设它会包含正确的路径...
  • 另外,这似乎只适用于文本编辑器,而不是例如图片查看器。
【解决方案3】:
import * as vscode from "vscode";
import * as fs from "fs";   

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

以上代码用于查找当前在vscode上激活的文件路径。

vscode.window.activeTextEditor 获取编辑器的引用,document.uri.fsPath 以字符串格式返回该文件的路径

【讨论】:

    【解决方案4】:

    以下是windows中vscode返回的各种路径示例:

    扩展路径:

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

    当前文件夹:

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

    当前编辑器文件:

    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 
    

    请注意,pathfsPath 指的是同一个文件夹。 fsPath 以适合操作系统的形式提供路径。

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 2017-12-25
      相关资源
      最近更新 更多