VSCode 扩展写入和打开文件

mak*_*kim 5 file-io visual-studio-code vscode-extensions

我的要求其实很简单,我想写一个文件并在vscode中打开它。但我无法让它工作:

var content = rec[rt.fields[field]];
var filePath = path.join(vscode.workspace.rootPath, selected.label + '.' + field);
fs.writeFileSync(filePath, content, 'utf8');

var openPath = vscode.Uri.parse(filePath);
vscode.workspace.openTextDocument(openPath).then(doc => {
  vscode.window.showTextDocument(doc);
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息,但不知道这意味着什么:

无法打开 c:%5CUsers%5Cmak%5C.sneditor%5Csoftpointdev1.service-now.com%5CRMCostPlanHelper.js。详细信息:没有 uri 'c:%5CUsers%5Cmak%5C.sneditor%5Csoftpointdev1.service-now.com%5CRMCostPlanHelper.js' 的模型,也没有方案“c”的解析器。

小智 10

我也遇到了类似的问题。您还可以通过执行以下操作来解决您的问题:

var content = rec[rt.fields[field]];
var filePath = path.join(vscode.workspace.rootPath, selected.label + '.' + field);
fs.writeFileSync(filePath, content, 'utf8');

var openPath = vscode.Uri.parse("file:///" + filePath); //A request file path
vscode.workspace.openTextDocument(openPath).then(doc => {
  vscode.window.showTextDocument(doc);
});
Run Code Online (Sandbox Code Playgroud)


mak*_*kim 9

一发布这个问题,我就找到了答案^^

你必须使用vscode.Uri.filevscode.Uri.parse

const content = 'exampleContent';
const filePath = path.join(vscode.workspace.rootPath, 'fileName.extension');
fs.writeFileSync(filePath, content, 'utf8');

const openPath = vscode.Uri.file(filePath);
vscode.workspace.openTextDocument(openPath).then(doc => {
    vscode.window.showTextDocument(doc);
});
Run Code Online (Sandbox Code Playgroud)