Search code examples
c#cakebuild

Cake (C# make) use .Net Framework methods in build.cake


Maybe a dump question. Cake states that its a build automation system that can be written in C#. I'm actually playing around a bit and now want to know if it is possible to call .Net methods in build.cake. At the time I've the following build.cake:

var target = Argument("target", "Default");

Task("NuGet")
   .Does(() =>
   {
       // Get local directory
       // Get all packages.config files in local directory
       // Call nuget restore for every file
       var currentDir =  System.IO.GetCurrentDirectory(); // This doesn't work
       var allPgkConfigs = System.IO.Directory.GetFiles(currentDir, "packages.config", System.IO.SearchOption.AllDirectories); // This doesn't work

       foreach (var pgk in allPgkConfigs)
       {
           // GetNuGetPackageId(pkg);
       }
       
   });

Task("Build")
  .Does(() =>
{
  MSBuild("MySolution.sln");
});

RunTarget(target);

When calling build.ps1 -target nuget I get the following error:

PS C:\> .\build.ps1 -Target nuget
Preparing to run build script... 
Running build script...
Analyzing build script...
Processing build script...
Compiling build script...
Error: C:/Users/Mewald-T550/XAP_Playground/build.cake(6,26): error CS0234: The type or namespace name 'GetCurrentDirectory' does not exist in the namespace 'System.IO' (are you missing an assembly reference?) 

As cake already states it can't find System.IO how can I add this reference to cake?

I know that cake offers some build-in file operations, but I want to know how to add .Net Framework methods to the cake script.

Thx


Solution

  • You're calling a method on a namespace

    Change

    System.IO.GetCurrentDirectory()
    

    to

    System.IO.Directory.GetCurrentDirectory()
    

    Tried this script and it worked just fine

    var directory = System.IO.Directory.GetCurrentDirectory();
    Information(directory);
    

    That said, Cake has several IO abstractions built in

    I.e. this will achieve the same:

    var allPgkConfigs = GetFiles("./**/packages.config");
    foreach (var pgk in allPgkConfigs)
    {
       // GetNuGetPackageId(pkg);
    }
    

    If you just want the current directory you can use

    Context.Environment.WorkingDirectory
    

    or just

    var curDir = MakeAbsolute(Directory("./"));
    Information("Current directory is: {0}", curDir);