如何:使用 VSProject2 对象操作 Visual Basic 和 C# 项目

更新:2007 年 11 月

VSProject2 接口提供特定于 Visual C#、Visual Basic 和 Visual J# 项目的方法和属性的访问权限。VSProject2 还通过 DTEProject 属性,提供常规环境模型的 DTEProject 对象的访问权限。

VSProject2 的大多数方法和属性都可统一地应用于 Visual C#、Visual Basic 和 Visual J# 项目。唯一的例外情况是 Imports 属性,它应用于 Visual Basic 并提供 Imports 对象的访问权限。有关更多信息,请参见 如何:操作 Visual Basic 项目的 Imports 属性Events 属性提供对特定于项目的事件(例如 VSLangProjWebReferencesEventsReferencesEvents)的访问。事件处理任务在其他主题中介绍。有关更多信息,请参见响应事件(Visual Basic 和 Visual C# 项目)

下面的步骤演示如何使用常规自动化模型以编程方式创建 Visual C# Windows 应用程序。VSProject2 的方法和属性用于以编程方式控制创建的项目。

ms228960.alert_note(zh-cn,VS.90).gif说明:

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您的当前设置或版本。这些过程是使用现用的常规开发设置开发的。若要更改设置,请在“工具”菜单上选择“导入和导出设置”。有关更多信息,请参见 Visual Studio 设置

使用 VSProject2 对象控制 C# 和 J# 项目

  1. 使用 Visual C# 创建 Visual Studio 外接程序项目。

  2. 在“项目”菜单上单击“添加引用”,再单击“.NET”选项卡,选择“VSLangProj”、“VSLangProj2”和“VSLangProj80”,然后单击“确定”。

  3. 在计算机上创建两个文件夹:

    • <安装根目录>\UserFiles\MyProjects\MyTestProject。

    • <安装根目录>\UserFiles\MyKeyFiles。

      在此示例中,<安装根目录> 为“C:”。

  4. 将以下 using 语句添加到 Connect.cs 文件顶部。

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    
  5. 将下面的方法调用添加到 OnConnection 方法。

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        CSVSProj2Manip(_applicationObject);
    }
    
  6. 添加 CSVSProj2Manip 方法声明,使其紧跟在 OnConnection 方法的下方。

    public void CSVSProj2Manip(DTE2 dte)
    {
    }
    
  7. 将下面的声明添加到此方法的顶部。

    Solution2 soln = (Solution2)_applicationObject.Solution;
    String csTemplatePath;
    String csPrjPath;
    Project proj;
    VSProject2 vsproj;
    String webServiceRef;
    BuildManager bldMgr;
    
  8. 使用 AddFromTemplate 创建一个 Visual C# 项目。

    • 获取模板的语法为 EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "CSharp"),其中的名称 " WindowsApplication.zip " 从位于 <安装根目录>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\CSharp\Windows\2052 文件夹中的 WindowsApplication.zip 文件获得。对于所有 Visual Studio 项目类型,都可以在 <安装根目录>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\语言 文件夹中找到这些文件。"CSharp" 指定该项目为 Visual C# 项目。

    • 对于 Visual Basic Windows 应用程序项目,语法为 EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "VisualBasic")。对于 Visual Basic 项目,可以在 <安装根目录>\ Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\VisualBasic\Windows\2052 文件夹中找到 Windows 应用程序 zip 文件模板。

    • 对于 Visual J# Windows 应用程序项目,语法为 EnvDTE80.Solution2.GetProjectTemplate("WindowsApplication.zip", "JSharp")。对于 Visual J# 项目,可以在 <安装根目录>\Program Files\Microsoft Visual Studio 8\Common7\IDE\ProjectTemplates\JSharp\Windows\2052 文件夹中找到 Windows 应用程序 zip 文件模板。

    // Make sure you create the folders that 
    // make up the file path
    // on your computer. You can replace 
    // this with your own file path.
    csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
    // Get the project template path for a C# windows 
    // application.
    csTemplatePath = soln.GetProjectTemplate("WindowsApplication.zip", "CSharp");
    // Create a new windows application by using the 
    // template obtained above.
    soln.AddFromTemplate(csTemplatePath, csPrjPath,
     "Test2CSProj", false);
    
  9. 添加下面的代码来演示 VSProject2 方法的用法。

    若要以编程方式将 Web 服务添加到此项目,则必须用实际 Web 服务的 URL 替换代码中的占位符文本 <web service>。若要定位 Web 服务 URL,请在 Visual Studio 集成开发环境 (IDE) 中打开一个项目。在“项目”菜单上单击“添加 Web 引用”。在“添加引用”对话框中单击“UDDI 目录”链接,并使用该目录查找 Web 服务。

    proj = soln.Projects.Item(1);
    // Cast the project as a VSProject2 object.
    vsproj = (VSProject2)proj.Object;
    // Add a reference to System.Security.dll.
    MessageBox.Show("Adding a reference 
    to System.Security.dll");
    // Remove the <version number> in the following path
    // and replace it with one of the version 
    // number folders that appear 
    // in <installation root>\WINDOWS\Microsoft.NET\Framework
    // folder
    vsproj.References.Add
    ("C:\\WINDOWS\\Microsoft.NET\\Framework\\<version number>\\System.Security.dll");
    // Create a Web references folder.
    MessageBox.Show("Creating a Web references folder.");
    vsproj.CreateWebReferencesFolder();
    // Add a Web reference to the folder.
    MessageBox.Show("Adding a Web reference.");
    // Replace the placeholder, <web service>, with a
    // Web service URL.
    webServiceRef = "<web service>";
    vsproj.AddWebReference(webServiceRef);
    bldMgr = vsproj.BuildManager;
    Array monikers = null;
    // String moniker = null;
    String msg = null;
    Object obj = bldMgr.DesignTimeOutputMonikers;
    if (obj != null)
    {
        try
        {
            monikers = (System.Array)obj;
            foreach(String tempmoniker in monikers)
            {
                msg += bldMgr.BuildDesignTimeOutput
    (tempmoniker) + "\n";
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        MessageBox.Show("The build design-time output is:" 
    + "\n"  + msg);
    }
    // Change the MyHTML file name by using GetUniqueFilename.
    MessageBox.Show("Adding an HTML page named 'MyHTML'...");
    String itemTemplatePath = soln.GetProjectItemTemplate("HTMLPage",
     "CSharp");
    proj.ProjectItems.AddFromTemplate
    (itemTemplatePath, "MyHtml");
    MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
    vsproj.Project.ProjectItems.Item("MyHtml").Name =
     vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
    // Generate a key-pair file.
    MessageBox.Show("Generating a key-file...");
    vsproj.GenerateKeyPairFiles("C:\\UserFiles\\MyKeyFiles
    \\MyKeyText2.bin", "0");
    

    CSVSProj2Manip 方法使用 VSProject2 对象执行以下操作:

    示例部分列出了完整的代码,其中包括整个方法的 try-catch 块。

  10. 若要生成外接程序,请单击“生成”菜单上的“生成解决方案”。

  11. 在 Visual Studio IDE 中打开一个 Visual C#、Visual J# 或 Visual Basic 项目。

  12. 在“工具”菜单上单击“外接程序管理器”,再从“外接程序管理器”对话框中选择您要的外接程序。单击“确定”以运行外接程序。

  13. 通过使用强名称工具 (Sn.exe),查看在 <安装根目录>\UserFiles\MyKeyFiles 文件夹中生成的密钥对文件。

示例

下面的示例是一个简单的 Visual Studio 外接程序,它创建一个 Visual C# 项目,并通过使用 VSProject2 对象的属性和方法对该项目进行操作。

using System;
using System;
using Extensibility;
using EnvDTE;
using EnvDTE80;
using System.Windows.Forms;
using VSLangProj;
using VSLangProj2;
using VSLangProj80;
public void OnConnection(object application, 
ext_ConnectMode connectMode, object addInInst, ref Array custom)
{
    _applicationObject = (DTE2)application;
    _addInInstance = (AddIn)addInInst;
    CSVSProj2Manip(_applicationObject);
}
public void CSVSProj2Manip(DTE2 dte)
{
    try
    {
        Solution2 soln = (Solution2)_applicationObject.Solution;
        String csTemplatePath;
        String csPrjPath;
        Project proj;
        VSProject2 vsproj;
        String webServiceRef;
        BuildManager bldMgr;
        // Make sure you create the folders that make up the file path
        // on your computer.
        // You can replace this with your own file path.
        csPrjPath = "C:\\UserFiles\\MyProjects\\MyTestProject";
        // Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate
("WindowsApplication.zip", "CSharp");
        // Create a new Windows application by using the template 
        // obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath,
 "Test2CSProj", false);
        proj = soln.Projects.Item(1);
        // Get a reference to the VSProject2 object.
        vsproj = (VSProject2)proj.Object;
        // Add a reference to System.Security.dll.
        MessageBox.Show("Adding a reference to System.Security.dll");
        // Remove the <version number> in the following path
        // and replace it with one of the version 
        // number folders that appear 
        // in <installation root>\WINDOWS\Microsoft.NET\Framework
        // folder
        vsproj.References.Add
("C:\\WINDOWS\\Microsoft.NET\\Framework\\<version number>\\System.Security.dll");
        // Create a Web references folder.
        MessageBox.Show("Creating a Web references folder.");
        vsproj.CreateWebReferencesFolder();
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        MessageBox.Show("Adding a Web reference.");
        // Replace the placeholder, <web service>, with a
        // Web service URL.
        webServiceRef = "<web service>";
        vsproj.AddWebReference(webServiceRef);
        bldMgr = vsproj.BuildManager;
        Array monikers = null;
        // String moniker = null;
        String msg = null;
        Object obj = bldMgr.DesignTimeOutputMonikers;
        if (obj != null)
        {
            try
            {
                monikers = (System.Array)obj;
                foreach(String tempmoniker in monikers)
                {
                    msg += bldMgr.BuildDesignTimeOutput(tempmoniker) 
+ "\n";
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            MessageBox.Show("The build design-time output is:" + "\n"  
+ msg);
        }
        // Change the MyHTML file name by using GetUniqueFilename.
        MessageBox.Show("Adding an HTML page named 'MyHTML'...");
        String itemTemplatePath =
 soln.GetProjectItemTemplate("HTMLPage", "CSharp");
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml");
        MessageBox.Show("Renaming MyHtml' to 'MyTesthtml.htm'...");
        vsproj.Project.ProjectItems.Item("MyHtml").Name =
 vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm");
        // Generate a key-pair file.
        MessageBox.Show("Generating a key-file...");
        vsproj.GenerateKeyPairFiles
("C:\\UserFiles\\MyKeyFiles\\MyKeyText2.bin", "0");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports EnvDTE80
Imports VSLangProj
Imports VSLangProj2
Imports VSLangProj80
Public Sub OnConnection(ByVal application As Object, _
 ByVal connectMode As ext_ConnectMode, ByVal addInInst As Object, _
 ByRef custom As Array) Implements IDTExtensibility2.OnConnection
    _applicationObject = CType(application, DTE2)
    _addInInstance = CType(addInInst, AddIn)
    CSVSProj2Manip(_applicationObject)
End Sub
Sub CSVSProj2Manip(ByVal dte As DTE2)
    Try
        Dim soln As Solution2 = CType(_applicationObject.Solution, _
         Solution2)
        Dim csTemplatePath As String
        Dim csPrjPath As String
        Dim proj As Project
        Dim vsproj As VSProject2
        Dim webServiceRef As String
        Dim bldMgr As BuildManager
        ' Create this or your own file path on your computer.
        ' The file path must exist before you run this add-in.
        csPrjPath = "C:\UserFiles\MyProjects\MyTestProject"
        ' Get the project template path for a C# windows application.
        csTemplatePath = soln.GetProjectTemplate _
        ("WindowsApplication.zip","CSharp")
        ' Create a new Windows Application
        ' using the template obtained above.
        soln.AddFromTemplate(csTemplatePath, csPrjPath _
        , "Test2CSProj", False)
        proj = soln.Projects.Item(1)
        ' Cast the project to a VSProject2.
        vsproj = CType(proj.Object, VSProject2)
        ' Add a reference to System.Security.dll.
        MsgBox("Adding a reference to System.Security.dll")
        ' Remove the <version number> in the following path
        ' and replace it with one of the version 
        ' number folders that appear 
        ' in <installation root>\WINDOWS\Microsoft.NET\Framework
        ' folder
        vsproj.References.Add _
        ("C:\WINDOWS\Microsoft.NET\Framework\<version number>\System.Security.dll")
        ' Create a Web references folder.
        MsgBox("Creating a Web references folder.")
        vsproj.CreateWebReferencesFolder()
        ' Replace the placeholder, <web service>, with a
        ' web service URL.
        webServiceRef = "<web service>"
        MsgBox("Adding a Web reference.")
        vsproj.AddWebReference(webServiceRef)
        bldMgr = vsproj.BuildManager
        Dim monikers As String() = Nothing
        Dim moniker As String = Nothing
        Dim msg As String = ""
        Dim obj As Object = bldMgr.DesignTimeOutputMonikers
        If Not obj Is Nothing Then
            Try
                monikers = CType(obj, String())
                For Each moniker In monikers
                    msg &= bldMgr.BuildDesignTimeOutput(moniker) + vbCr
                Next
            Catch ex As System.Exception
                MsgBox(ex.ToString)
            End Try
            MsgBox("The build design-time output is:" + vbCr + msg)
        End If
        ' Use the UniqueFilename to rename a new project item.
        MsgBox("Adding an HTML page called 'MyHTML'...")
        Dim itemTemplatePath As String = _
        soln.GetProjectItemTemplate("HTMLPage", "CSharp")
        proj.ProjectItems.AddFromTemplate(itemTemplatePath, "MyHtml")
        MsgBox("Renaming MyHtml' to 'MyTesthtml.htm'...")
        vsproj.Project.ProjectItems.Item("MyHtml").Name = _
        vsproj.GetUniqueFilename(proj, "MyTesthtml", "htm")
        ' Generate a key-pair file.
        vsproj.GenerateKeyPairFiles _
        ("C:\UserFiles\MyKeyFiles\MyKeyText2.bin", "0")
    Catch ex As System.Exception
        MsgBox(ex.ToString)
    End Try
End Sub

编译代码

若要编译此代码,请创建一个新的 Visual Studio 外接程序项目,然后用本示例中的代码替换 OnConnection 方法的代码。有关如何运行外接程序的信息,请参见 如何:使用外接程序管理器控制外接程序

请参见

概念

VSProject2 对象介绍

其他资源

扩展 Visual Basic 和 Visual C# 项目