5

I'm trying to create a file as a part of one of the commands in my extension and can't seem to get it right.

let wsedit = new vscode.WorkspaceEdit(); const file_path = vscode.Uri.file(value + '/' + value + '.md'); vscode.window.showInformationMessage(file_path.toString()); wsedit.createFile(file_path, {ignoreIfExists: true}); vscode.workspace.applyEdit(wsedit); vscode.window.showInformationMessage('Created a new file: ' value + '/' + value + '.md); 

value is a string input from the user. The code executes, but from what I can tell no file is being created. How do I properly create the file?

2 Answers 2

11
+100

It seems like the vscode.Uri does not support relative paths (here is the corresponding issue). With that said you have to use an absolute path. The following snippet should work (tested on windows with vscode v1.30.0)

const wsedit = new vscode.WorkspaceEdit(); const wsPath = vscode.workspace.workspaceFolders[0].uri.fsPath; // gets the path of the first workspace folder const filePath = vscode.Uri.file(wsPath + '/hello/world.md'); vscode.window.showInformationMessage(filePath.toString()); wsedit.createFile(filePath, { ignoreIfExists: true }); vscode.workspace.applyEdit(wsedit); vscode.window.showInformationMessage('Created a new file: hello/world.md'); 
Sign up to request clarification or add additional context in comments.

4 Comments

I'm getting an error for your first line there that states "Object is possibly 'undefined'". Any thoughts?
on const wsedit = new vscode.WorkspaceEdit();? Maybe you can just add my line two and three into your snippet and give it a try. (Btw. I used typescript)
I was able to accomplish it by using a form of this answer. After getting the object I then check to make sure that it's not undefined.
at least for a VS Code Web extension I had to do: const filePath = vscode.Uri.joinPath(vscode.workspace.workspaceFolders[0].uri, '/hello/world.md')
0

You can achieve the same with (writeFile)[https://code.visualstudio.com/api/references/vscode-api#workspace.fs.writeFile], with much lesser code.

vscode.workspace.fs.writeFile(filePath, Buffer.from('')) 

It creates the file and directories as needed. Caution: it will replace the contents of the file if it exists.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.