views:

48

answers:

3

I'm creating a simple .NET console application where I want to save a file in a folder that's part of the root project, like so: SolutionName.ProjectName\TestData\. I want to put test.xml into the TestData folder. However, when I go to save my XDocument, it saves it to SolutionName.ProjectName\bin\x86\Debug Console\test.xml.

What do I need to do to save or retrieve the file in a folder that is a child of project directory?

A: 

You can use the System.IO namespace to get your directory relative to your exe:

var exeDirectory = Application.StartupPath;
var exeDirectoryInfo = new DirectoryInfo(exeDirectory);
var projectDirectoryInfo = exeDirectoryInfo.Parent.Parent.Parnet; // bin/x86/debug to project

var dataPath = Path.Combine(projectDirectoryInfo.FullName, "TestData");

var finalFilename = Path.Combine(dataPath, "test.xml");
Reed Copsey
@Reed I was thinking about going that route, and I like the suggestion, but I can't find `Application.StartupPath`. How do I find that (or similar) in a Console Application?
Ben McCormack
+1  A: 

I've seen this before but never actually tried it out. Did a quick search and dug this up:

System.AppDomain.CurrentDomain.BaseDirectory

Give that a shot instead of Application.StartupPath for your console app.

L1Wulf
+2  A: 

Your console application is, once compiled, not really related to your Visual Studio solution anymore. The best way is probably to simply 'feed' the output path to your application as an command line argument:

Public Sub Main(args as String())

   ' don't forget validation: handle situation where no or invalid arguments supplied

    Dim outputFile = Path.Combine(args(0), "TestData", "test.xml")

End Sub

Now you can run your application like so:

myapp.exe Path\To\SolutionFolder
jeroenh