views:

555

answers:

4

I have a visual studio solution that comprises of several projects and are separated into different directories.

In my c# or vb.net code I want to determine the base directory (or the directory that the solution is in).

A dirty solution would be to call the directory parent.parent.parent until I find a file *.sln but I also have several solutions in other directories that I dont want to be returned.

I am just wondering if there is a cleaner method maybe part of System.Diagnostics.Debugger or similar?

I look forward to your reply, thanks.

A: 

Even though you have solutions in other directories, presumably those aren't directories within your original solution, are they? What situation do you envisage where the "recurse up until you find a .sln file" would fail (other than running from the wrong directory)?

One alternative would be to pass the solution directory as a command line argument.

What do you need this for, out of interest?

Jon Skeet
+1  A: 

As the sln file does not need to be deployed on the target machine - why are you trying to find it at all?
If you still want to use the sln- try at EnvDTE Namespace

EnvDTE.DTE dte = (EnvDTE.DTE) System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
string folder = System.IO.Path.GetDirectoryName(dte.ActiveDocument.FullName);

Dror
A: 

Is the code being run from within the solution, i.e. within the IDE debugger? If so you can pass the solution directory as $(SolutionDir) from the IDE to the command line.

ChrisW
A: 

Thank you for your answers. All were very helpful. I worked with the answer from Dror and with a little modification to the following line solved this problem, thanks.

string folder = System.IO.Path.GetDirectoryName(dte.Solution.FullName);

The reason I want to do this is whilst running the code in the IDE I determine the current Subversion revision of the project so that I can embed this into the running software version.

This is done automatically. See the article I wrote at codeproject: link text

If you look at the code you will see I perform the following: dirinfoSourceWorkingDir = dirInfo.Parent().Parent().Parent();

I need to determine the directory of the solution currently open in Visual Studio but want a cleaner way (and if I change the directory structure this would break the code).

Hope this makes sense!

Belliez