Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Usare la Project Query API per leggere e modificare progetti, file e proprietà in una soluzione Visual Studio.
Note
Questa guida usa VisualStudio.Extensibility SDK. Vedi Scegliere il modello di estendibilità corretto per il confronto dei modelli.
Esempio completo
Implementazione completa:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace VSProjectQueryAPISample;
using System.Globalization;
using System.Text;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Commands;
using Microsoft.VisualStudio.Extensibility.Shell;
using Microsoft.VisualStudio.ProjectSystem.Query;
/// <summary>
/// A sample command for querying the project system.
/// </summary>
[VisualStudioContribution]
public class QueryFileCommand : Command
{
/// <inheritdoc />
public override CommandConfiguration CommandConfiguration => new("%VSProjectQueryAPISample.QueryFileCommand.DisplayName%")
{
Placements = [CommandPlacement.KnownPlacements.ToolsMenu],
Icon = new(ImageMoniker.KnownValues.Extension, IconSettings.IconAndText),
};
/// <inheritdoc />
public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
{
var result = await this.Extensibility.Workspaces().QueryProjectsAsync(
project => project.With(project => project.Name)
.With(project => project.Path)
.With(project => project.Files.With(file => file.FileName)),
cancellationToken);
StringBuilder message = new StringBuilder($"\n \n === Querying File === \n");
foreach (var project in result)
{
_ = message.Append(CultureInfo.CurrentCulture, $"{project.Name}\n");
foreach (var file in project.Files)
{
_ = message.Append(CultureInfo.CurrentCulture, $" \t {file.FileName}\n");
}
}
await this.Extensibility.Shell().ShowPromptAsync(message.ToString(), PromptOptions.OK, cancellationToken);
}
}
Tip
Visualizza l'esempio completo funzionante: VSProjectQueryAPISample ↗
Concetti correlati:Concetti di progetto — architettura del sistema di progetto e modelli di query
Capire l’esempio
Ottieni l'area di lavoro
WorkspacesExtensibility workspace = this.Extensibility.Workspaces();
workspace.Queryable consente di accedere allo spazio interrogabile del progetto radice per query e sottoscrizioni avanzate. Per le query comuni, usare gli helper QueryProjectsAsync e QuerySolutionAsync illustrati di seguito.
Osservare l'apertura e la chiusura della soluzione
QueryableSpaceChanged viene eseguito in modo asincrono quando una soluzione viene aperta o chiusa.
SolutionPath è null in chiusura. Mantieni attivo il listener finché sono necessarie notifiche e rimuovi la sottoscrizione quando viene eliminato:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.ProjectSystem.Query;
internal sealed class SolutionChangeListener : IDisposable
{
private readonly WorkspacesExtensibility workspace;
public SolutionChangeListener(VisualStudioExtensibility extensibility)
{
this.workspace = extensibility.Workspaces();
this.workspace.QueryableSpaceChanged += this.OnChangedAsync;
}
private Task OnChangedAsync(ProjectQueryableSpaceChangedEventArgs args)
{
Trace.WriteLine(args.SolutionPath is null
? "Solution closed"
: $"Solution opened: {args.SolutionPath}");
return Task.CompletedTask;
}
public void Dispose()
{
this.workspace.QueryableSpaceChanged -= this.OnChangedAsync;
}
}
Ottieni il documento attivo e il progetto attivo
In un comando il contesto client acquisisce lo stato dell'IDE corrente. L'URI del documento attivo e lo snapshot del progetto possono essere entrambi assenti:
Uri? documentUri = await context.GetActiveDocumentUriAsync(cancellationToken);
IProjectSnapshot? activeProject = await context.GetActiveProjectAsync(cancellationToken);
Vedere il comando ↗ del progetto attivo per un esempio che gestisce un progetto mancante. L'URI del documento riflette la selezione attiva al momento della creazione del contesto, non una visualizzazione dinamica delle modifiche successive.
Eseguire query sui progetti con proprietà
// Get all projects with name, path, and GUID
IQueryResults<IProjectSnapshot> projects = await workspace.QueryProjectsAsync(
project => project.With(p => p.Name)
.With(p => p.Path)
.With(p => p.Guid),
cancellationToken);
Filtrare i progetti in base alla capacità
// Get only .NET Core web projects
IQueryResults<IProjectSnapshot> webProjects = await workspace.QueryProjectsAsync(
project => project.Where(p => p.Capabilities.Contains("DotNetCoreWeb"))
.With(p => p.Path)
.With(p => p.Guid),
cancellationToken);
Interrogare i file di progetto
// Get all files in a specific project
IQueryResults<IFileSnapshot> files = await workspace.QueryProjectsAsync(
project => project.Where(p => p.Guid == knownGuid)
.Get(p => p.Files.With(f => f.FileName)),
cancellationToken);
Aggiungere un file a un progetto
IQueryResults<IProjectSnapshot> updated = await workspace.UpdateProjectsAsync(
project => project.Where(p => p.Guid == knownGuid),
project => project.CreateFile("NewFile.cs"),
cancellationToken);
Rinominare un file
await workspace.UpdateProjectsAsync(
project => project.Where(p => p.Guid == knownGuid),
project => project.RenameFile(oldPath, newName),
cancellationToken);
Creare un progetto
// Build entire solution
IQueryResults<ISolutionSnapshot> solutions = await this.Extensibility.Workspaces().QuerySolutionAsync(
s => s, cancellationToken);
foreach (var solution in solutions)
{
await solution.AsQueryable().BuildAsync(cancellationToken);
}
// Build a single project by name
var result = await this.Extensibility.Workspaces().QueryProjectsAsync(
project => project.Where(p => p.Name == "MyApp"),
cancellationToken);
await result.First().BuildAsync(cancellationToken);
Cercare pacchetti NuGet
// Get all package references for a project
IQueryResults<IProjectSnapshot> result = await workspace.QueryProjectByGuidAsync(
project => project.With(p => p.ActiveConfigurations
.With(c => c.PackageReferences
.With(pkg => pkg.Name)
.With(pkg => pkg.Version))),
knownGuid,
cancellationToken);
Proprietà del progetto della query
IQueryResults<IProjectSnapshot> props = await workspace.QueryProjectsAsync(
project => project.With(p => p.PropertiesByName("RootNamespace", "AssemblyVersion")),
cancellationToken);
Eseguire una query sulla soluzione
IQueryResults<ISolutionSnapshot> solution = await workspace.QuerySolutionAsync(
s => s.With(sol => sol.Path)
.With(sol => sol.Guid)
.With(sol => sol.ActiveConfiguration),
cancellationToken);
Tips
✅ DO
- Usare
.With()sempre per specificare le proprietà necessarie - Filtrare in base alla funzionalità prima di accedere alle proprietà specifiche della funzionalità
- Usa
UpdateProjectsAsyncper le mutazioni - Passa
CancellationTokena tutte le chiamate asincrone
❌ DON'T
- Non eseguire interrogazioni senza filtri — le soluzioni molto grandi saranno lente
- Non presupporre che tutti i tipi di progetto supportino tutte le proprietà (ad esempio, progetti SQL)
- Non tentare di modificare
IProjectSnapshotdirettamente: è immutabile - Non usare
CancellationToken.Nonenelle estensioni in produzione
🔧 Risoluzione dei problemi
| Sintomo | Correzione |
|---|---|
| La proprietà genera un'eccezione | Controllare prima PropertiesAvailableStatus |
| La query restituisce risultati vuoti | Il filtro non ha trovato alcuna corrispondenza: verificare le capacità o i nomi del progetto |
CreateFile Fallisce |
Verificare che il progetto sia caricato e scrivibile |
| Proprietà specifiche della funzionalità mancanti | Usare WithRequired per filtrare i progetti che hanno effettivamente la proprietà |