VSCode - Raccourci pour compiler le projet C# actif
Découvrez comment créer un raccourci clavier dans Visual Studio Code qui compile uniquement le projet C# sur lequel vous travaillez, plutôt que l’ensemble de la solution. Ce guide vous explique comment configurer un raccourci clavier personnalisé Ctrl+B
qui détecte automatiquement le fichier .csproj
le plus proche de votre fichier actif et le compile rapidement. Idéal pour les solutions volumineuses où vous souhaitez éviter les longs temps de compilation et vous concentrer sur le test de projets spécifiques pendant le développement.
Prerequisites
Si vous avez besoin d’instructions détaillées sur l’installation de toutes les extensions requises pour exécuter un projet C# dans VSCode, veuillez vous reporter à l’article de blog : Comment configurer C# dans VSCode.
Étapes pour configurer les raccourcis clavier personnalisés
Vous pouvez suivre les étapes suivantes pour configurer le raccourci clavier personnalisé Ctrl+B
dans VSCode afin de compiler le projet csproj
actuel à partir du fichier actif.
Voici les étapes à suivre :
- Créez un script PowerShell
build-current-project.ps1
:- Ce script recherche automatiquement le fichier
.csproj
le plus proche en remontant l’arborescence des répertoires à partir du fichier actif actuel. - Si aucun fichier
.csproj
n’est trouvé, il affiche un message d’erreur. - Il fournit des informations claires sur ce qu’il compile.
- Ce script recherche automatiquement le fichier
- Ajoutez une tâche VSCode :
- Exécuter le script PowerShell avec le chemin d’accès du fichier actuellement actif
- Utiliser des outils de détection des problèmes appropriés pour détecter les erreurs
- Configurer pour fonctionner avec l’environnement de travail
- Configurez le raccourci clavier
Ctrl+B
:- Exécute la tâche
build-current-project
lorsque vous appuyez surCtrl+B
- Activer uniquement lorsque le texte est sélectionné dans l’éditeur
- Exécute la tâche
1. Script ./.vscode/build-current-project.ps1
:
Copiez et collez ce script Powershell dans ce fichier enregistré dans le dossier .vscode
.
# PowerShell script to find and build the nearest .csproj file
param(
[string]$CurrentFile = $env:VSCODE_ACTIVE_FILE,
[string]$WorkspaceFolder = $env:WORKSPACE_FOLDER
)
# Function to find the nearest .csproj file
function Find-NearestProject {
param([string]$StartPath)
$currentDir = Split-Path -Parent $StartPath
while ($currentDir -and $currentDir -ne [System.IO.Path]::GetPathRoot($currentDir)) {
# Look for .csproj files in current directory
$csprojFiles = Get-ChildItem -Path $currentDir -Filter "*.csproj" -ErrorAction SilentlyContinue
if ($csprojFiles) {
# Return the first .csproj found
return $csprojFiles[0].FullName
}
# Move up one directory
$currentDir = Split-Path -Parent $currentDir
}
return $null
}
# Main execution
try {
if (-not $CurrentFile) {
Write-Host "No active file detected." -ForegroundColor Red
Write-Host "Error: No .csproj file found" -ForegroundColor Red
exit 1
} else {
Write-Host "Active file: $CurrentFile" -ForegroundColor Green
$nearestProject = Find-NearestProject -StartPath $CurrentFile
if ($nearestProject) {
$projectPath = $nearestProject
Write-Host "Found nearest project: $projectPath" -ForegroundColor Green
} else {
Write-Host "Error: No .csproj file found" -ForegroundColor Red
exit 1
}
}
# Build the project
Write-Host "Building: $projectPath" -ForegroundColor Cyan
& dotnet build "$projectPath" --configuration Debug
if ($LASTEXITCODE -eq 0) {
Write-Host "Build completed successfully!" -ForegroundColor Green
} else {
Write-Host "Build failed with exit code $LASTEXITCODE" -ForegroundColor Red
exit $LASTEXITCODE
}
}
catch {
Write-Host "Error: $_" -ForegroundColor Red
exit 1
}
2. Ajouter une tâche VSCode
Mettez à jour ou créez le fichier ./vscode/tasks.json
avec le contenu suivant :
{
"version": "2.0.0",
"tasks": [
"tasks": [
// Ctrl+Shift+B → To run the default build task (build-solution)
{
"label": "build-solution",
"type": "shell",
"command": "dotnet",
"args": [
"build",
"Microsoft.FluentUI-v5.sln", // 👈 Update this line with your default solution file name
"--configuration",
"Debug"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$msCompile",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"options": {
"cwd": "${workspaceFolder}"
}
},
// Ctrl+B → Build current project based on active file
{
"label": "build-current-project",
"type": "shell",
"command": "powershell.exe",
"args": [
"-NoProfile",
"-ExecutionPolicy",
"Bypass",
"-File",
"${workspaceFolder}/.vscode/build-current-project.ps1"
],
"group": "build",
"problemMatcher": "$msCompile",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared",
"showReuseMessage": true,
"clear": false
},
"options": {
"cwd": "${workspaceFolder}",
"env": {
"VSCODE_ACTIVE_FILE": "${file}",
"WORKSPACE_FOLDER": "${workspaceFolder}"
}
}
}
]
}
3. Configurer le raccourci clavier Ctrl+B
Si vous avez déjà installé l’extension Visual Studio Keymap, Ctrl+Shift+B
est déjà configuré pour compiler l’ensemble de la solution. Si ce n’est pas le cas, vous pouvez appuyer sur ces touches et sélectionner la tâche à compiler build-solution
.
Pour configurer Ctrl+B
afin d’exécuter la tâche build-current-project
, créée à l’étape précédente, vous devez ouvrir le fichier keybindings.json
: allez dans la barre de recherche en haut de VSCode et recherchez Open Keyboard Shortcuts (JSON)
.
Mettez à jour ce fichier avec ces raccourcis. Les deux premiers suppriment les raccourcis existants pour permettre l’utilisation d’un nouveau raccourci.
[
{
"key": "ctrl+b",
"command": "-workbench.debug.viewlet.action.addFunctionBreakpointAction"
},
{
"key": "ctrl+b",
"command": "-workbench.action.toggleSidebarVisibility"
}, {
"key": "ctrl+b",
"command": "workbench.action.tasks.runTask",
"args": "build-current-project",
"when": "editorTextFocus"
},
]