James Ko James Ko -4 years ago 139
C# Question

How would I call a constructor defined in C# from MSBuild?

I'm trying to convert this C# code to run in MSBuild:

var uri = new Uri(s1);

var result = uri.MakeRelativeUri(new Uri(s2)).ToString();

I'm not quite sure how you would call the
constructor from MSBuild, though. Here is what I have so far:

<!-- <FirstUri>???</FirstUri>
<SecondUri>???</SecondUri> -->

As you can see, I've commented out the
snippets because I couldn't figure out how to get them to work. I've tried
new Uri($(FirstString))
, but that just caused it to be subsituted with the literal value of s1 (e.g.
"new Uri(C:\Users)"

How do I get this to work? Any help would be appreciated, thanks!

edit: Well, it looks like it's not possible from straight MSBuild. I've accepted Mark Arnott's answer of creating a custom MSBuild task, although I don't think I'll be doing this by myself.

Perhaps if you were running on Windows-only clients, you could do something like this:

<Exec Command="powershell '(New-Object [System.Uri] ...'" />

I'm a bit hesitant to start a whole new process just to create relative paths though, so that's a bit of a dealbreaker.

Answer Source

I am not sure what your goal is, but if you really need MSBuild to run some C# code, you need to use inline tasks. See MSDN's Walkthrough: Creating an Inline Task

Most of the time MSBuild runs pre-compiled tasks and command line utilities.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download