Поделиться через


Практическое руководство. Доступ к свойствам папок определенных типов проектов

Свойства папки можно установить вручную и проверить в проекте в интегрированной среде разработки Visual Studio, щелкнув папку правой кнопкой мыши в Обозревателе решений. Чтобы открыть диалоговое окно Свойства, в контекстном меню выберите Свойства.

Пространство имен VSLangProj80 предлагает способ программного доступа к свойствам папок в проектах Visual C# или Visual Basic. В частности, FolderProperties2 определяет большой набор свойств для управления и сведениями о папке и доступа к ним. Ко многим свойствам, определенным в FolderProperties2, невозможен ручной доступ из окна Свойства.

Чтобы получить доступ к определенному свойству FolderProperties2, необходимо указать точное имя свойства в виде строки в EnvDTE.Property.Properties.Item(object index), как показано в следующем примере кода.

Project project;
ProjectItem folder;
Properties folderProps;
Property prop;
project = _applicationObject.Solution.Projects.Item(1);
folder = project.ProjectItems.AddFolder("MyFolder"
,Constants.vsProjectItemKindPhysicalFolder);
folderProps = folder.Properties;
prop = folderProps.Item("FullPath");

Этот код обращается к свойству FullPath папки в проекте Visual C# или Visual Basic.

В действительности, свойства, определенные в FolderProperties2, представляют собой список доступных свойств папок, к которым можно получить доступ как к элементам свойств проектов Visual C# или Visual Basic.

В следующих шагах подробно описан порядок программного доступа к этим свойствам в надстройке Visual Studio.

Примечание

Отображаемые на компьютере имена или расположения некоторых элементов пользовательского интерфейса Visual Studio могут отличаться от указанных в следующих инструкциях.Эти элементы определяются используемым выпуском Visual Studio и его параметрами.Для получения дополнительной информации см. Настройка параметров разработки в Visual Studio.

Доступ к свойствам папок для определенного типа проекта

  1. Создайте проект надстройки Visual Studio, используя Visual C#.

  2. В меню Проект щелкните Добавить ссылку, перейдите на вкладку .NET выберите VSLangProj, VSLangProj2 и VSLangProj80, и нажмите кнопку ОК.

  3. Добавьте в начало файла Connect.cs следующие операторы using.

    using VSLangProj;
    using VSLangProj2;
    using VSLangProj80;
    
  4. Добавьте в метод OnConnection следующий вызов метода.

    public void OnConnection(object application, 
    ext_ConnectMode connectMode, object addInInst, ref Array custom)
    {
        _applicationObject = (DTE2)application;
        _addInInstance = (AddIn)addInInst;
        VSProjectFolderProps2(_applicationObject);
    }
    
  5. Добавьте метод VSProjectFolderProps2 сразу после метода OnConnection.

    public void VSProjectFolderProps2(DTE2 dte)
    {
        try
        {
            // Open a Visual C# or Visual Basic project
            // before running this add-in.
            Project project;
            ProjectItem folder;
            Properties folderProps;
            Property prop;
            project = _applicationObject.Solution.Projects.Item(1);
            // Add a new folder to the project.
            MessageBox.Show("Adding a new folder to the project.");
            folder =
     project.ProjectItems.AddFolder("MyFolder",
    Constants.vsProjectItemKindPhysicalFolder);
            folderProps = folder.Properties;
            prop = folderProps.Item("FullPath");
            MessageBox.Show("The full path of the new folder is:" 
    + "\n" + prop.Value.ToString());
            prop = folderProps.Item("FileName");
            MessageBox.Show("The file name of the new folder is:" 
    + "\n" + prop.Value.ToString());
            prop = folderProps.Item("URL");
            MessageBox.Show("The new folder has the following URL:" 
    + "\n" + prop.Value.ToString());
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    

    В разделе примера представлен полный код.

  6. Чтобы построить надстройку, в меню Построение щелкните Построить решение.

  7. Откройте проект Visual C# или Visual Basic в интегрированной среде разработки Visual Studio.

  8. В меню Свойства щелкните Диспетчер надстроек и в диалоговом окне Диспетчер надстроек выберите надстройку. Нажмите ОК для выполнения надстройки.

    Свойства папки для FullPath, FileName и URL отображены в окнах сообщений.

Пример

Ниже приведен пример простой надстройки Visual Studio, которая демонстрирует доступ к свойствам папки в определенном типе проекта при помощи автоматизации в Visual Studio.

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;
    VSProjectFolderProps2(_applicationObject);
}
public void VSProjectFolderProps2(DTE2 dte)
{
    try
    {
        // Open a Visual C# or Visual Basic project
        // before running this add-in.
        Project project;
        ProjectItem folder;
        Properties folderProps;
        Property prop;
        project = _applicationObject.Solution.Projects.Item(1);
        // Add a new folder to the project.
        MessageBox.Show("Adding a new folder to the project.");
        folder =
 project.ProjectItems.AddFolder("MyFolder"
,Constants.vsProjectItemKindPhysicalFolder);
        folderProps = folder.Properties;
        prop = folderProps.Item("FullPath");
        MessageBox.Show("The full path of the new folder is:" + "\n" 
+ prop.Value.ToString());
        prop = folderProps.Item("FileName");
        MessageBox.Show("The file name of the new folder is:" + "\n" 
+ prop.Value.ToString());
        prop = folderProps.Item("URL");
        MessageBox.Show("The new folder has the following URL:" 
+ "\n" + prop.Value.ToString());
    }
    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)
    VSProjectConfigProperties(_applicationObject)
End Sub
Sub VSProjectConfigProperties(ByVal dte As DTE2)
    ' Open a Visual C# or Visual Basic project
    ' before running this add-in.
    Try
        Dim project As Project
        Dim folder As ProjectItem
        Dim folderProps As Properties
        Dim prop As [Property]
        project = _applicationObject.Solution.Projects.Item(1)
        ' Add a new folder to the project.
        MsgBox("Adding a new folder to the project...")
        folder = project.ProjectItems.AddFolder("MyFolder" _
        , Constants.vsProjectItemKindPhysicalFolder)
        folderProps = folder.Properties
        prop = folderProps.Item("FullPath")
        MsgBox("The full path of the new folder is:" & vbCr _
        & prop.Value.ToString())
        prop = folderProps.Item("FileName")
        MsgBox("The file name of the new folder is:" & vbCr _
        & prop.Value.ToString())
        prop = folderProps.Item("URL")
        MsgBox("The new folder has the following URL:" & vbCr  _
        & prop.Value.ToString())
    Catch ex As System.Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Компиляция кода

Для компиляции кода создайте новый проект надстройки Visual Studio и замените код метода OnConnection кодом из данного примера. Сведения о запуске надстройки см. в разделе Практическое руководство. Управление надстройками с помощью диспетчера надстроек.

См. также

Другие ресурсы

Project Properties

Доступ к свойствам Project, Project Item и Configuration, специфическим для типа проекта