Como: Especificar eventos de compilação (C#)

Use build events to specify commands that run before the build starts or after the build finishes. Build events are executed only if the build successfully reaches those points in the build process.

Quando um projeto é criado, eventos Pre-Build são adicionados a um arquivo chamado PreBuildEvent. bat e eventos Post-Build são adicionados a um arquivo chamado PostBuildEvent. Se você deseja garantir a verificação de erros, adicione seus próprios comandos de verificação de erros para as etapas de criação.

ObservaçãoObservação

Seu computador pode mostrar nomes ou locais diferentes para alguns dos elementos da interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Configurações do Visual Studio.

How to Specify Pre-Build and Post-Build Events

To specify a build event

  1. In Solution Explorer, select the project for which you want to specify the build event.

  2. On the Project menu, click Properties.

  3. Select the Build Events tab.

  4. In the Pre-build event command line box, specify the syntax of the build event.

    ObservaçãoObservação

    Pre-build events do not run if the project is up to date and no build is triggered.

  5. In the Post-build event command line box, specify the syntax of the build event.

    ObservaçãoObservação

    Add a call statement before all post-build commands that run .bat files. For example, call C:\MyFile.bat or call C:\MyFile.bat call C:\MyFile2.bat.

  6. In the Run the post-build event box, specify under what conditions to run the post-build event.

    ObservaçãoObservação

    To add lengthy syntax, or to select any build macros from the Evento/Post-build linha de comando caixa de diálogo evento de pré-compilação, click the Ellipsis button () to display an edit box.

    The build event syntax can include any command that is valid at a command prompt or in a .bat file. The name of a batch file should be preceded by call to ensure that all subsequent commands are executed.

    Nota se o seu evento Pre-Build ou Post-Build não for concluída com êxito, você pode finalizar a compilação fazendo com que a ação de evento fechado com um código diferente de zero (0), que indica uma ação bem-sucedida.

Exemplo: Como alterar as informações de manifesto usando um evento de pós-compilação

The following procedure shows how to set the minimum operating system version in the application manifest by using an .exe command that is called from a post-build event (the .exe.manifest file in the project directory). The minimum operating system version is a four-part number such as 4.10.0.0. To do this, the command will change the <dependentOS> section of the manifest:

<dependentOS>
   <osVersionInfo>
      <os majorVersion="4" minorVersion="10" buildNumber="0" servicePackMajor="0" />
   </osVersionInfo>
</dependentOS>

To create an .exe command to change the application manifest

  1. Create a console application for the command. From the File menu, point to New, and then click Project.

  2. In the New Project dialog box, expand Visual C#, click Windows, and then click the Console Application template. Name the project ChangeOSVersionCS.

  3. In Program.cs, add the following line to the other using statements at the top of the file:

    using System.Xml;
    
  4. In the ChangeOSVersionCS namespace, replace the Program class implementation with the following code:

    class Program
    {
       /// <summary>
       /// This function will set the minimum operating system version for a ClickOnce application.
       /// </summary>
       /// <param name="args">
       /// Command Line Arguments:
       /// 0 - Path to application manifest (.exe.manifest).
       /// 1 - Version of OS
       ///</param>
       static void Main(string[] args)
       {
          string applicationManifestPath = args[0];
          Console.WriteLine("Application Manifest Path: " + applicationManifestPath);
    
          // Get version name.
          Version osVersion = null;
          if (args.Length >=2 ){
             osVersion = new Version(args[1]);
          }else{
             throw new ArgumentException("OS Version not specified.");
          }
          Console.WriteLine("Desired OS Version: " + osVersion.ToString());
    
          XmlDocument document;
          XmlNamespaceManager namespaceManager;
          namespaceManager = new XmlNamespaceManager(new NameTable());
          namespaceManager.AddNamespace("asmv1", "urn:schemas-microsoft-com:asm.v1");
          namespaceManager.AddNamespace("asmv2", "urn:schemas-microsoft-com:asm.v2");
    
          document = new XmlDocument();
          document.Load(applicationManifestPath);
    
          string baseXPath;
          baseXPath = "/asmv1:assembly/asmv2:dependency/asmv2:dependentOS/asmv2:osVersionInfo/asmv2:os";
    
          // Change minimum required operating system version.
          XmlNode node;
          node = document.SelectSingleNode(baseXPath, namespaceManager);
          node.Attributes["majorVersion"].Value = osVersion.Major.ToString();
          node.Attributes["minorVersion"].Value = osVersion.Minor.ToString();
          node.Attributes["buildNumber"].Value = osVersion.Build.ToString();
          node.Attributes["servicePackMajor"].Value = osVersion.Revision.ToString();
    
          document.Save(applicationManifestPath);
       }
    }
    

    O comando leva dois argumentos: o caminho do manifesto do aplicativo (ou seja, a pasta na qual o processo de compilação cria o manifesto, geralmente Projectname.publish) e a nova versão do sistema operacional.

  5. Build the project. Sobre o Build menu, clique em Build Solution.

  6. Copy the .exe file to a directory such as C:\TEMP\ChangeOSVersionVB.exe.

Next, invoke this command in a post-build event to modify the application manifest.

To invoke a post-build event to modify the application manifest

  1. Create a Windows application for the project to be published. From the File menu, point to New, and then click Project.

  2. In the New Project dialog box, expand Visual C#, click Windows, and then click the Windows Forms Application template. Name the project CSWinApp.

  3. With the project selected in Solution Explorer, on the Project menu, click Properties.

  4. In the Project Designer, locate the Publish page and set Publishing location to C:\TEMP\.

  5. Publish the project by clicking Publish Now.

    The manifest file will be built and put in C:\TEMP\CSWinApp_1_0_0_0\CSWinApp.exe.manifest. To view the manifest, right-click the file, click Open with, select Select the program from a list, and then click Notepad.

    Search in the file for the <osVersionInfo> element. For example, the version might be:

    <os majorVersion="4" minorVersion="10" buildNumber="0" servicePackMajor="0" />
    
  6. In the Project Designer, click the Build Events tab and click the Edit Post-build button.

  7. In the Post-build Event Command Line box, type the following command:

    C:\TEMP\ChangeOSVersionCS.exe "$(TargetPath).manifest" 5.1.2600.0

    When you build the project, this command will change the minimum operating system version in the application manifest to 5.1.2600.0.

    Because the $(TargetPath) macro expresses the full path for the executable being created, the $(TargetPath).manifest will specify the application manifest created in the bin directory. Publishing will copy this manifest to the publishing location that you set earlier.

  8. Publish the project again. Go to the Publish page and click Publish Now.

    View the manifest again. To view the manifest, open the publish directory, right-click the file, click Open with, select Select the program from a list, and then click Notepad.

    The version should now read:

    <os majorVersion="5" minorVersion="1" buildNumber="2600" servicePackMajor="0" />
    

Consulte também

Tarefas

Como: Especificar eventos de compilação (Visual Basic)

Referência

Página de eventos de compilação, Project Designer (C#)

Evento/Post-build linha de comando caixa de diálogo evento de pré-compilação

Outros recursos

Criando no Visual Studio