Create a Relative path code snippet

Here is a code snippet that is equivalent to the windows API PathRelativePathTo as native c#. The function creates a relative path from one file or folder to another.

public class PathUtil  
{  
    /// <summary>  
    /// Creates a relative path from one file  
    /// or folder to another.  
    /// </summary>  
    /// <param name="fromDirectory">  
    /// Contains the directory that defines the   
    /// start of the relative path.  
    /// </param>  
    /// <param name="toPath">  
    /// Contains the path that defines the  
    /// endpoint of the relative path.  
    /// </param>  
    /// <returns>  
    /// The relative path from the start  
    /// directory to the end path.  
    /// </returns>  
    /// <exception cref="ArgumentNullException"></exception>  
    public static string RelativePathTo(  
        string fromDirectory, string toPath)  
    {  
        if (fromDirectory == null)  
            throw new ArgumentNullException("fromDirectory");  
   
        if (toPath == null)  
            throw new ArgumentNullException("toPath");  
   
        bool isRooted = Path.IsPathRooted(fromDirectory)  
            && Path.IsPathRooted(toPath);  
   
        if (isRooted)  
        {  
            bool isDifferentRoot = string.Compare(  
                Path.GetPathRoot(fromDirectory),  
                Path.GetPathRoot(toPath), true) != 0;  
   
            if (isDifferentRoot)  
                return toPath;                           
        }                 
   
        StringCollection relativePath = new StringCollection();  
        string[] fromDirectories = fromDirectory.Split(  
            Path.DirectorySeparatorChar);  
   
        string[] toDirectories = toPath.Split(  
            Path.DirectorySeparatorChar);  
   
        int length = Math.Min(  
            fromDirectories.Length,  
            toDirectories.Length);  
   
        int lastCommonRoot = -1;  
   
        // find common root  
        for (int x = 0; x < length; x++)  
        {  
            if (string.Compare(fromDirectories[x],  
                toDirectories[x], true) != 0)  
                break;  
   
            lastCommonRoot = x;  
        }  
        if (lastCommonRoot == -1)  
            return toPath;  
   
        // add relative folders in from path  
        for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)  
            if (fromDirectories[x].Length > 0)  
                relativePath.Add("..");  
   
        // add to folders to path  
        for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)  
            relativePath.Add(toDirectories[x]);  
   
        // create relative path  
        string[] relativeParts = new string[relativePath.Count];  
        relativePath.CopyTo(relativeParts, 0);  
   
        string newPath = string.Join(  
            Path.DirectorySeparatorChar.ToString(),  
            relativeParts);  
   
        return newPath;  
    }  
}  

Draco.NET version 1.6.4.0 Released

I’ve update and released a new version of Draco.NET. This release is mainly to make it compatible with Visual Studio 2005 and MSBuild. The following is a list of changes …

1.6-release-2 (1.6.4.0)

  • Added MSBuild support
  • Added Visual Studio 2005 support
  • Added manual build (no polling) support
  • Improved project config web page
  • Fixed bug where error emails were sent repeatedly

What is Draco.NET?

Draco.NET is a Windows service application designed to facilitate continuous integration. Draco.NET monitors your source code repository, automatically rebuilds your project when changes are detected and then emails you the build result along with a list of changes since the last build.

Get the latest

http://sourceforge.net/project/showfiles.php?group_id=66880


Sample build file using MSBuild Community Tasks

The MSBuild Community Tasks Project has released the first version of tasks. The following is a sample build project that uses the SvnVersion, AssemblyInfo, NDoc and Zip tasks to create a release.

Import Targets

The first thing that needs to be done in the build file is to import the MSBuild.Community.Tasks.Targets file that defines the available tasks. If you use the msi installer to install the MSBuild Community Tasks, you can use the path “$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets”.

Version Target

The first target in the sample file is the Version target. The version target is used to update the latest version number. First the SvnVersion task is used to get the latest Revision number from the local working subversion repository. SvnVersion outputs the Revision to the Revision property.

Next the target uses the AssemblyInfo task to generate an AssemblyInfo.cs file with the attributes specified.

Compile Target

The compile target calls msbuild to compile the solution in release mode. The MSBuild target will compile the solution the exact same way Visual Studio will.

Documentation Target

To create help for the project, there is the documentation target. In the documentation target, the NDoc task is used to compile a HTML Help project. To use the NDoc task, you must have NDoc 1.3.1 installed.

The generated HTML Help file is then moved to the documentation folder and the temp files are cleaned up.

Zip Target

The zip target is used to package up the whole project into a zip file. Zip target uses the Zip task to create the zip. The files included in the zip are selected by the ItemGroup ZipFiles.

Sample Master.proj File

<?xml version="1.0" encoding="utf-8"?>  
  
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">  
  <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>  
   
  <PropertyGroup>  
   <Major>1</Major>  
    <Minor>0</Minor>  
    <Build>0</Build>  
    <Revision>0</Revision>  
  </PropertyGroup>  
  
  <ItemGroup>  
    <DefaultExclude Include="**\.svn\**" />  
    <DefaultExclude Include="**\bin\**" />  
    <DefaultExclude Include="**\obj\**" />  
    <DefaultExclude Include="**\Release\**" />  
    <DefaultExclude Include="**\Debug\**" />  
    <DefaultExclude Include="**\Test\**" />  
    <DefaultExclude Include="**\TestResults\**" />  
    <DefaultExclude Include="**\doc\**" />  
    <DefaultExclude Include="**\www\**" />  
    <DefaultExclude Include="**\*.user" />  
    <DefaultExclude Include="**\*.suo" />  
    <DefaultExclude Include="**\*.zip" />  
    <DefaultExclude Include="**\*.txt" />  
  </ItemGroup>  
   
  <ItemGroup>  
    <ZipFiles Include="**\*.*" Exclude="@(DefaultExclude)" />  
  </ItemGroup>  
   
  <Target Name="Version">  
    <SvnVersion LocalPath="$(MSBuildProjectDirectory)">  
      <Output TaskParameter="Revision" PropertyName="Revision" />  
    </SvnVersion>  
   
    <Message Text="Version: $(Major).$(Minor).$(Build).$(Revision)"/>  
   
    <AssemblyInfo CodeLanguage="CS"   
      OutputFile="Source\MSBuild.Community.Tasks\Properties\AssemblyInfo.cs"  
      AssemblyTitle="MSBuild Community Tasks"  
      AssemblyDescription="Collection MSBuild Tasks"  
      AssemblyCompany="http://msbuildtasks.tigris.org/"  
      AssemblyProduct="MSBuild.Community.Tasks"  
      AssemblyCopyright="Copyright © Paul Welter 2005"       
      ComVisible="false"  
      CLSCompliant="true"  
      Guid="d038566a-1937-478a-b5c5-b79c4afb253d"  
      AssemblyVersion="$(Major).$(Minor).$(Build).$(Revision)"  
      AssemblyFileVersion="$(Major).$(Minor).$(Build).$(Revision)"  
      Condition="$(Revision) != '0' "/>  
   
  </Target>  
   
  <Target Name="Compile" DependsOnTargets="Version">  
    <MSBuild Projects="Source\MSBuild.Community.Tasks.sln"  
             Properties="Configuration=Release" />  
  </Target>  
   
  <Target Name="Documentation" DependsOnTargets="Compile">  
    <NDoc Documenter="MSDN"  
          ProjectFilePath="Documentation\MSBuild.Community.Tasks.ndoc" />  
   
    <Copy SourceFiles="doc\MSBuild Community Tasks.chm"  
          DestinationFiles="Documentation\MSBuild.Community.Tasks.chm" />  
   
    <RemoveDir Directories="doc" />  
   
  </Target>  
   
  <Target Name="Zip" DependsOnTargets="Documentation">  
    <Zip Files="@(ZipFiles)"  
         ZipFileName="MSBuild.Community.Tasks.v$(Major).$(Minor).$(Build).$(Revision).zip" />  
  </Target>  
   
  <Target Name="Build" DependsOnTargets="Zip">  
    <Message Text="CodeSmith Build Complete"/>  
  </Target>  
   
</Project>

I hope this sample will help in creating build files for your project.

~ Paul


MSBuild Community Tasks Project releases version v1.0.0.29

Announcement

The MSBuild Community Tasks Project releases version v1.0.0.29. The following is a list of tasks.

Current Community Tasks

Task Description
AssemblyInfo Generates an AssemblyInfo file using the attributes given.
FtpUpload Uploads a file using File Transfer Protocol (FTP).
Mail Sends an email message.
Math.Add Add numbers.
Math.Divide Divide numbers.
Math.Multiple Multiple numbers.
Math.Subtract Subtract numbers.
NDoc Runs NDoc V1.3.1 to create documentation.
NUnit Runs tests using the NUnit V2.2 framework.
RegistryRead Reads a value from the Registry.
RegistryWrite Writes a value to the Registry.
SvnCheckout Checkout files from Subversion
SvnClient Subversion Client
SvnCommit Commit files to Subversion
SvnExport Export files from Subversion
SvnUpdate Update files from Subversion
SvnVersion Get Subversion revision number of a local copy
Unzip Unzip a file to a target directory.
Version Increments a four-part version number stored in a text file
XmlRead Reads a value from a XML document using a XPath.
XmlWrite Updates a XML document using a XPath.
Zip Create a zip file with the files specified.

Join Project

Please join the MSBuild Community Tasks Project and help contribute in building the tasks. 

http://msbuildtasks.tigris.org/

Get The Source

You can get a local copy of the repository for MSBuild Community Tasks via Subversion. The following command will do the trick:

svn checkout http://msbuildtasks.tigris.org/svn/msbuildtasks/trunk

Download The Latest

The latest binaries, source and installer for Windows can be found in this directory of the Tigris file-sharing area.


MSBuild Community Task Collaboration Project

I’d like to announce the MSBuild Community Task Collaboration Project. The project was started by me to form a directory of MSBuild Tasks for use in your build scripts. The project is also an open source collection of tasks. The project is broke into 2 web sites.

The first is http://msbuildtasks.com/ which is a community server install with forums and a directory of MSBuild tasks. The goal of msbuildtasks.com is to provide a common place to find tasks. Please help improve this directory by adding links to tasks that you know about.

The second site is an open source project hosted at http://msbuildtasks.tigris.org/. The goal of this site is to build a collection of tasks that is open source for the community. Please create an account on Tigris.org and join the project to help build out the tasks.

Thanks for contributing to the MSBuild community.

~ Paul