简体   繁体   中英

Save/retrieve a file in a project directory, not the output directory

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?

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.

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

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM