SharpSvn: A Primer

The SharpSvn library basically gives you a .NET interface to all the operations that you would normally perform through a tool like TortoiseSVN.

I found myself needing this exact library while writing a tool that changes files that have been checked out from SVN.

The problem with manipulating files that are under SVN is that you need to be careful about renaming files (and sometimes even deleting). If you don’t do it through the SVN api then you will end up with duplicates files/folders in SVN since SVN thinks that it’s a new file.

To solve this I finally got a chance to crack open the SharpSVN library which is used by my favourite AnkhSVN.

1. Download the latest library from http://sharpsvn.open.collab.net/. You have to pick between either 1.5 or 1.6. I went with 1.6 and didn’t run into any issues. I think this is based on the version of the SVN server that your connecting to.

2. In your Visual Studio project add a reference to the following assemblies.
– SharpSvn.dll
– SharpSvn.UI.dll (Only needed if you need the UI to prompt for login)

3. If like me your building on a 64 bit OS and you want your app to run on a 32 bit OS, make sure the project that references the SharpSvn.dll is set to Build for the x86 Platform. (Build –> Configuration Manager – Solution Platform)

4. Write your code using the SvnClient object. Here are some samples from the SharpSvn Wiki and some that I wrote.

CheckOut

public void CheckOut()
{
  using (SvnClient client = new SvnClient())
  {
     client.CheckOut(
       new Uri("http://svn.collab.net/repos/svn/trunk/contrib"),
       @"c:\wc");
  } 
}

Add new files to the working copy

using(SvnClient client = new SvnClient())
{
  SvnAddArgs args = new SvnAddArgs();
  // TODO: Set optional settings on args

  client.Add(@"C:\file\in\workingcopy", args);
}

Check if a given path is a valid SVN working copy

public static bool IsWorkingCopy(string path)
{
    using (var client = GetSvnClient())
    {
        var uri = client.GetUriFromWorkingCopy(path);

        return uri != null;
    }
}

Find out if a particular folder/file has been marked for deletion.

public static bool IsDeleted(string path)
{
    if(!IsWorkingCopy(path)) return false;

    bool isDeleted;
    using (var client = GetSvnClient())
    {
        Collection<SvnStatusEventArgs> args;
        client.GetStatus(path, out args);
        isDeleted = args.Count > 0 && args[0].LocalContentStatus == SvnStatus.Deleted;
    }
    return isDeleted;
}
 
What’s even more awesome about the guys who wrote this library actively support it (even over twitter, thanks http://twitter.com/srijken!).
 
And that was even before I found out that they have a ready made .wxs file for integrating the .dlls into my WiX installer package. Awesome!
SharpSvn: A Primer