【问题标题】:Can a Visual Studio Code Task generate a file and automatically open it in the same windowVisual Studio Code Task 能否生成文件并在同一窗口中自动打开
【发布时间】:2019-08-17 11:08:47
【问题描述】:

我有一个 C# 任务,它在我的 VSCode 工作区文件夹中生成一个文件。

我希望文件在生成后自动打开。目前我能做的最好的事情是打印文件的全名,以便用户可以 Ctrl+单击链接。

环境设置:

  • 在空文件夹中打开 VSCode。
  • 创建一个新的 C# 控制台应用程序(在终端中输入 dotnet new console)。
  • 更新Program.cs:
namespace VSCodeOpenGeneratedFile
{
    using System;
    using System.IO;

    class Program
    {
        static void Main(string[] args)
        {
            File.WriteAllText("test.txt", "Hello world!");
            Console.WriteLine(Path.Combine(Directory.GetCurrentDirectory(), "test.txt"));
        }
    }
}

  • 添加.vscode/tasks.json:
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Generate File",
            "command": "dotnet run",
            "type": "shell",
            "problemMatcher": []
        }
    ]
}
  • 运行任务:
    • Ctrl+Shift+P
    • 选择任务:运行任务
    • 选择生成文件
  • TERMINAL 中您应该会看到文件名,您可以 Ctrl+单击打开。

如何让任务自动打开此文件?

【问题讨论】:

  • 您的任务可能会尝试在终端中调用code "full/path/to/test.txt"。但是,即使有可能,我认为这会在新的 vscode 实例中打开 test.txt

标签: c# visual-studio-code vscode-tasks


【解决方案1】:

我发现您可以使用command line arguments for VS code 完成此操作。使用 -r--reuse-window 参数,您可以在当前的 VS 代码窗口中打开一个文件。

在使用此任务创建过时的降价文件后,我能够做到这一点:

{
  "label": "new note",
  "type": "shell",
  "command": "set -lx t (date +%Y-%m-%d-%H-%M-%S);echo \"# $t\" > ${workspaceFolder}/notes/$t.md;code -r ${workspaceFolder}/notes/$t.md"
}

这是在带有 fish shell 的 Linux 上,但您应该能够对 Windows 或其他 shell 使用类似的命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2018-02-08
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多