gonzobrains
gonzobrains

Reputation: 8036

Visual Studio: How to add code templates to project

I would like to create a feature that allows me to automatically add a few related files to my C# project. I want to create a new form based on a template, and create an XML file and add it to a separate sub-directory within the project. How would I go about doing this? I see that there are wizards, add-ins, macros, etc. available in Visual Studio 2008, but I do not know which is most appropriate for my needs. I thought a wizard would work, but that may be overkill. I just want to remove the repetitiveness of copying from an existing set of files within the same project.

Upvotes: 1

Views: 1760

Answers (1)

WarrenG
WarrenG

Reputation: 3084

You can export individual project items as zipped templates using the menu File|Export Template... in VS2010. To create a template with multiple files, you can export the first item, then add additional items to the resulting template zip. You'll also need to edit the .vstemplate file in the zip to include the additional items.

As an example, I exported a form from a existing project and then added an xml file. The resulting zip file contains the files

__TemplateIcon.ico
Form1.cs
Form1.Designer.cs
Form1.resx
MyTemplate.vstemplate
xmldata.xml

The .vstemplate file contains the following xml:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>TwoFileTemplate</DefaultName>
    <Name>TwoFileTemplate</Name>
    <Description>Test template</Description>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="" TargetFileName="xml\$fileinputname$.xml" ReplaceParameters="true">xmldata.xml</ProjectItem>
    <ProjectItem SubType="Form" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">Form1.cs</ProjectItem>
    <ProjectItem SubType="" TargetFileName="$fileinputname$.Designer.cs" ReplaceParameters="true">Form1.Designer.cs</ProjectItem>
    <ProjectItem SubType="" TargetFileName="$fileinputname$.resx" ReplaceParameters="true">Form1.resx</ProjectItem>
  </TemplateContent>
</VSTemplate>

Once you've updated the zip file, move it to the folder ...\Visual Studio 2010\Templates\ItemTemplates.

The new template should now show up in the Add New Item dialog in VS2010. It will add the form and xml file with whatever name you specify when adding the new item to the project and will put the xml file in a directory named 'xml'. If you want a fixed name for one or the other of the files you can replace $fileinputnam$ in the .vstemplate file with the desired name.

Edit - If you want a fixed item name for a form or other class file you'll also need to open the code templates and replace $safeitemname$ with the desired name.

Upvotes: 1

Related Questions