Automatically finding missing and duplicate files in CSProj

Posted on Updated on

It’s not uncommon for your CSProj files to become corrupted, or at least invalidated, during a merge. This typically happens when merging two relatively large pieces of work and often takes the form of:

  1. Files referenced in the CSProj that do not exist on disk
  2. Files that exist on disk, are needed for the project to compile but are not included in the CSProj
  3. Files that are on disk and are included, but multiple times

Since this can be quite a pain to fix (the process involves loading the project in Visual Studio and trying to build, getting an error in the concerned project, fixing and trying again) I wrote a simple Powershell script that will analyse your CSProj file and will return all the duplicate file includes as well as all the included files that do not exist on disk. This is a solution for points 1 and 3 above only, as point 2 (finding files on disk that are not included in the CSProj) is a slightly harder problem. I will come back to that in a later revision of the script.

This works well (it’s extremely simple) at displaying errors in your Proj file, but so far you must actually solve the problems manually. It strikes me that actually fixing the CSProj file could also be done automatically, so I am going to revisit this soon (any automatic fixes will, of course, be displayed before they are actually performed and will require the user’s consent to continue).

Here’s the script, I’ll see you back here soon for the two extra features mentioned above.

Param(
  [string]$filePath = $(throw "You must supply a file path")
)

$xml = ([xml] ( gc $filePath ))

$filesIncluded = $xml.Project.ItemGroup.Compile | select -ExpandProperty Include

$invalidPaths = foreach($path in $filesIncluded)
{
    $fullPath = Join-Path (split-path $filePath) $path

    if(-not (test-path $fullPath)){
        $path
    }
}

$uniquePaths = $filesIncluded | select –unique

$duplicatePaths = Compare-object –referenceobject $uniquePaths –differenceobject $filesIncluded `
| select -ExpandProperty InputObject

if($invalidPaths)
{
    ""
    "---- Invalid paths ----"
    $invalidPaths
}

if($duplicatePaths)
{
    ""
    "---- Duplicate paths ----"
    $duplicatePaths
}


if((-not $invalidPaths) -and (-not $duplicatePaths))
{
    "=> No errors found in $filePath"
}

""

One thought on “Automatically finding missing and duplicate files in CSProj

    […] Automatically finding missing and duplicate files in CSProj […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s