English
Français

Blog of Denis VOITURON

for a better .NET world

VSCode - Shortcut to build the current C# project

Posted on 2025-08-12

Learn how to create a powerful productivity shortcut in Visual Studio Code that builds only the current C# project you’re working on, instead of the entire solution. This guide shows you how to set up a custom Ctrl+B keybinding that automatically detects the nearest .csproj file from your active file and builds it quickly. Perfect for large solutions where you want to avoid long build times and focus on testing specific projects during development.

Prerequisites

If you need detailed instructions on installing all the required extensions to run a C# project in VSCode, please refer to the blog post: How to set up C# in VSCode.

Steps to configure the custom keybinding

You can follow the steps to configure the custom keybinding Ctrl+B, in VSCode to build the current csproj project based on the active file.

The steps are:

  1. Create a PowerShell Script build-current-project.ps1:
    • This script automatically finds the nearest .csproj file by walking up the directory tree from the current active file.
    • If no .csproj is found, a message will be displayed.
    • Provides clear feedback about what it’s building
  2. Add a VSCode Task:
    • Executes the PowerShell script with the current active file path
    • Uses proper problem matchers for error detection
    • Configured to work with the workspace environment
  3. Configure the key shortcut Ctrl+B:
    • Runs the build-current-project task when you press Ctrl+B
    • Only active when the editor has text focus

1. Script ./.vscode/build-current-project.ps1:

Copy and paste this Powershell script to this file saved in the .vscode folder.

# 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. Add a VSCode Task

Update or create the file ./vscode/tasks.json with this content:

{
    "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": "pwsh",
            "args": [
                "-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. Configure the key shortcut Ctrl+B

If you already installed the Visual Studio Keymap extension, Ctrl+Shift+B is already configured to compile the entire solution. If this is not the case, you can press these keys and select the task to compile build-solution.

To configure Ctrl+B to run the task build-current-project, created in the previous step, you need to open the keybindings.json file: go to the search bar at the top of VSCode and search for Open Keyboard Shortcuts (JSON).

Update this file with these shortcuts. The first two delete existing shortcuts to allow the use of a new shortcut.

[
    {
        "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"
    },
]

Languages

EnglishEnglish
FrenchFrançais

Follow me

Recent posts