如何在 Visual Studio 和 Visual Studio 代码之间共享片段?

How to share snippets between Visual Studio and Visual Studio Code?

我有一些 Visual Studio Code 格式的 C# 片段,下面是一个例子(它的文件名是 csharp.[Print to console].code-snippets:

{
    "Print to console": {
        "scope": "csharp",
        "prefix": "p",
        "body": [
            "Console.WriteLine(${10:\"${20:hi}\"});"
        ],
        "description": "Print to console"
    }
}

Visual Studio 的代码片段似乎使用了一种非常不同的格式。一个例子是:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>cw</Title>
            <Shortcut>cw</Shortcut>
            <Description>Code snippet for Console.WriteLine</Description>
            <Author>Microsoft Corporation</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal Editable="false">
                    <ID>SystemConsole</ID>
                    <Function>SimpleTypeName(global::System.Console)</Function>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[$SystemConsole$.WriteLine($end$);]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

我可以在他们之间分享片段吗?

CodeSnippetStudio by Alessandro Del Sole is an open source Visual Studio Extension 允许维护 Visual Studio snippet 文件并将它们导出为 VS Code json 片段。

Code Snippet Studio is an extension for Visual Studio 2015 that makes it easy to create, edit, package, and share IntelliSense code snippets for Visual Studio 2015 and Visual Studio Code.

  • Create, edit, and save code snippets via convenient user interface and through a code editor that supports syntax-highlighting. You can save traditional .snippet files for Visual Studio 2015 and .json files for Visual Studio Code.

根据 the project's User's Guide (docx),该工具将允许您 open/import 现有 Visual Studio .snippet 和 VS Code .json 片段:

Opening Existing Code Snippets

You can open and edit existing .snippet and .json files by clicking ...

Code Snippet Studio will load the snippet file and will populate the user interface with the code, declarations, Imports, and References (where supported). So, you will be able to make further edits and to save back the code snippet.

打开后,您应该可以 export/save 将代码段添加到您选择的目标(jsonsnippet)。这将允许您在 Visual Studio 和 VS Code 之间共享代码片段。


请注意 an open issue 添加了对 Visual Studio 2017 的支持,其中作者提到 CodeSnippetStudio 也应该在 Visual Studio 2017 中可用,只是不用于生成 VSIX 包:

Hi guys, if you mean installing Studio on VS 2017, this is allowed.

If you mean generating packages for VS 2017, I would really love to add support.

如果您只是维护跨视觉 Studio/VS 代码支持的片段,前者就足够了。