C# 在 Visual Studio 2012 的所有源代码文件中插入版权声明/横幅
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12199409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inserting copyright notice/banner in all source code files in Visual Studio 2012
提问by Leniel Maccaferri
After some Googling I found this: Use a Visual Studio Macro to Insert Copyright Headers into Source Files. It looked promising:
经过一番谷歌搜索后,我发现了这一点:使用 Visual Studio 宏将版权标题插入源文件。看起来很有希望:
// <copyright file="Sample.cs" company="My Company Name">
// Copyright (c) 2012 All Rights Reserved
// </copyright>
// <author>Leniel Macaferi</author>
// <date>08/30/2012 11:39:58 AM </date>
// <summary>Class representing a Sample entity</summary>
When I tried Tools -> Macrosmenu option it wasn't there anymore in VS 2012. Here's the proof: Macros in Visual Studio 11 Developer Preview. They just dropped this functionality. :(
当我尝试Tools -> Macros菜单选项时,它在 VS 2012 中不再存在。这是证据:Visual Studio 11 Developer Preview 中的宏。他们只是放弃了这个功能。:(
So, I'm just curious to know which option I could use to add the copyright info to all existing source code files in my solution using Visual Studio 2012. Is there any standard way of doing this, using a template file (something related to T4 templates) or a PowerShellscript? I could write some code to iterate over the files with .csextension and add the copyright info but that is not what I'm after. I'd like to know about some tool to automate this process.
所以,我只是想知道我可以使用哪个选项将版权信息添加到使用 Visual Studio 2012 的解决方案中的所有现有源代码文件中。是否有任何标准方法可以使用模板文件(与 T4 templates) 还是PowerShell脚本?我可以编写一些代码来迭代带有.cs扩展名的文件并添加版权信息,但这不是我所追求的。我想知道一些工具来自动化这个过程。
采纳答案by coolmine
You could create a new snippet and just type cp + double tab to insert the notice where you want (needless to say you can change the keyword to whatever you want).
您可以创建一个新的片段,然后输入 cp + double tab 以在您想要的位置插入通知(不用说您可以将关键字更改为您想要的任何内容)。
The only problem with it is, from what I'm aware, snippets do not support time functions, so getting the current time for your date line seems impossible with this technique. A not so good workaround for this is to make the time fields editable (similar to how the mbox snippet works) and just insert the time manually.
唯一的问题是,据我所知,片段不支持时间函数,因此使用此技术获取日期线的当前时间似乎是不可能的。一个不太好的解决方法是使时间字段可编辑(类似于 mbox 片段的工作方式)并手动插入时间。
Here's an example on how a snippet looks. The bellow snippet will get the class name automatically and insert the copyright notice in the place where you type 'copyright' and double tab.
这是一个关于片段外观的示例。下面的代码段将自动获取类名,并在您键入“版权”和双选项卡的位置插入版权声明。
Method 1
方法一
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Copyright</Title>
<Shortcut>Copyright</Shortcut>
<Description>Code snippet for Copyright notice</Description>
<Author>author name</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal Editable="false">
<ID>classname</ID>
<Function>ClassName()</Function>
</Literal>
</Declarations>
<Code Language="csharp">
<![CDATA[// <copyright file="$classname$" company="My Company Name">
// Copyright (c) 2012 All Rights Reserved
// <author>Leniel Macaferi</author>
// </copyright>
]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
Method 2
方法二
Also, here's an example of a program you can make to do that for you.
此外,这里有一个程序示例,您可以为您执行此操作。
List<string> files = new List<string>()
{
"c:\Form1.cs",
"c:\Form2.cs",
};
foreach (string file in files)
{
string tempFile = Path.GetFullPath(file) + ".tmp";
using (StreamReader reader = new StreamReader(file))
{
using (StreamWriter writer = new StreamWriter(tempFile))
{
writer.WriteLine(@"// <copyright file=" + Path.GetFileNameWithoutExtension(file) + @" company=My Company Name>
// Copyright (c) 2012 All Rights Reserved
// </copyright>
// <author>Leniel Macaferi</author>
// <date> " + DateTime.Now + @"</date>
// <summary>Class representing a Sample entity</summary>
");
string line = string.Empty;
while ((line = reader.ReadLine()) != null)
{
writer.WriteLine(line);
}
}
}
File.Delete(file);
File.Move(tempFile, file);
}
Some error catching will be required of course. But this should give you the general idea how to construct an UI around it an add the files you will want to process.
当然需要一些错误捕获。但这应该让您大致了解如何围绕它构建 UI 并添加您要处理的文件。
Method 3
方法三
It's also possible to change the template for your classes that can be usually be found under:
也可以更改您的类的模板,通常可以在以下位置找到:
C:\Program Files (x86)\Microsoft Visual Studio <version>\Common7\IDE\ItemTemplates\CSharp33\
Sometimes editing ItemTemplatesCacheis also necessary to display the results.
有时也需要编辑ItemTemplatesCache来显示结果。
Here's an example template based on your question:
这是基于您的问题的示例模板:
using System;
using System.Collections.Generic;
$if$ ($targetframeworkversion$ >= 3.5)using System.Linq;
$endif$using System.Text;
/* <copyright file=$safeitemrootname$ company="My Company Name">
Copyright (c) 2012 All Rights Reserved
</copyright>
<author>Leniel Macaferi</author>
<date>$time$</date>
<summary>Class representing a Sample entity</summary>*/
namespace $rootnamespace$
{
class $safeitemrootname$
{
}
}
回答by Leniel Maccaferri
I'm going to add here a PowerShell script I found in this post: Powershell – Copyright header generator script. It captures what I had in mind before posting the question...
我将在这里添加一个我在这篇文章中找到的 PowerShell 脚本:Powershell – 版权所有标头生成器脚本。它捕捉了我在发布问题之前的想法......
param($target = "C:\MyProject", $companyname = "My Company")
$header = "//-----------------------------------------------------------------------
// <copyright file=""{0}"" company=""{1}"">
// Copyright (c) {1}. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------`r`n"
function Write-Header ($file)
{
$content = Get-Content $file
$filename = Split-Path -Leaf $file
$fileheader = $header -f $filename,$companyname
Set-Content $file $fileheader
Add-Content $file $content
}
Get-ChildItem $target -Recurse | ? { $_.Extension -like ".cs" } | % `
{
Write-Header $_.PSPath.Split(":", 3)[2]
}
I wrote about it with minor modifications to adapt it to my needs:
我写了一些小的修改来适应我的需要:
Inserting copyright notice/banner/header in all source code files with PowerShell
回答by Pakman
After losing work to some obscure PowerShell script (not the one added as an answer), I decided to create copyright.py. Example usage:
在失去了一些晦涩的 PowerShell 脚本(不是作为答案添加的脚本)之后,我决定创建copyright.py。用法示例:
C:\>python copyright.py "C:\users\me\documents\path\to\vsproject"
It recursively finds all *.cs files in the specified directory and prefixes them with the copyright text. It does not matter if other text already exists at the start of the file; it will be removed.
它递归地查找指定目录中的所有 *.cs 文件,并在它们前面加上版权文本。文件开头是否已存在其他文本并不重要;它将被删除。
Note:As a precaution, you should always backup your code before executing this script
注意:作为预防措施,您应该始终在执行此脚本之前备份您的代码
回答by Nikita G.
A simpler version of the code by @leniel-macaferi (no filename and company, just header):
@leniel-macaferi 的一个更简单的代码版本(没有文件名和公司,只有标题):
param($target = "C:\MyProject")
$header = "//-----------------------------------------------------------------------------
// Copyright (c) The Corporation. All rights reserved.
//-----------------------------------------------------------------------------
"
function Write-Header ($file)
{
$content = Get-Content $file
$filename = Split-Path -Leaf $file
$fileheader = $header
Set-Content $file $fileheader
Add-Content $file $content
}
Get-ChildItem $target -Recurse | ? { $_.Extension -like ".cs" } | % `
{
Write-Header $_.PSPath.Split(":", 3)[2]
}
To run, save the code in a new file (e.g. AddHeader.ps1) in the directory you want to recursively iterate through and execute .\AddHeader.ps1 .from PowerShell window.
要运行,请将代码保存在要递归迭代并.\AddHeader.ps1 .从 PowerShell 窗口执行的目录中的新文件(例如 AddHeader.ps1)中。
回答by Thaoden
In case this might still be interesting, there is the License header pluginthat can add a completey customizable header to any file on creation. Currently, this does work with VS2013, but not (yet?) with VS 2015.
如果这仍然很有趣,可以使用License 标头插件,它可以在创建时向任何文件添加完全可定制的标头。目前,这确实适用于 VS2013,但不适用于 VS 2015(还没有?)。
回答by Thaoden
As per the release notes(scroll down a bit), Visual Studio 16.6 allows to define a file_header_templaterule in .editorconfigthat can be used to create file banners.
按照发行说明(向下滚动位),Visual Studio的16.6允许定义file_header_template规则.editorconfig,可用于创建文件的横幅。

