首页 > 解决方案 > Visual Studio Code Task 能否生成文件并在同一窗口中自动打开

问题描述

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

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

环境设置:

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"));
        }
    }
}

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Generate File",
            "command": "dotnet run",
            "type": "shell",
            "problemMatcher": []
        }
    ]
}

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

标签: c#visual-studio-codevscode-tasks

解决方案


我发现您可以使用VS code 的命令行参数来完成此操作。使用-ror--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 使用类似的命令。


推荐阅读