jipot
jipot

Reputation: 94

c# OpenFileDialogue Initial directory using relative path

How can I set the initial directory to be where my test data exists?

var relPath = System.IO.Path.Combine( Application.StartupPath, "../../" )

dlg.Title = "Open a Credit Card List";
dlg.InitialDirectory = relPath ;

The default directory it opens up to is where the .exe exists: Project2\Project2\bin\Debug

I want it to open up by default in the Project2 folder where my test data exists. But it does not allow me to move up a parent directory. How do I get around this?

Upvotes: 1

Views: 804

Answers (2)

codemonkeh
codemonkeh

Reputation: 2152

To convert your relative path to an absolute path you can use Path.GetFullPath()

var relPath = System.IO.Path.Combine(Application.StartupPath, @"\..\..");
relPath = Path.GetFullPath(relPath);
dlg.InitialDirectory = relPath;

Alternatively if you wish to change the working directory to your test data:

Directory.SetCurrentDirectory(relPath);

More information: http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx http://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory.aspx

Upvotes: 0

Damith
Damith

Reputation: 63105

You can use Directory.GetParent(string path)

string relPath = Directory.GetParent(Application.StartupPath).Parent.FullName;

Or using DirectoryInfo

DirectoryInfo drinfo =new DirectoryInfo(path);

DirectoryInfo twoLevelsUp =drinfo.Parent.Parent;
dlg.InitialDirectory = twoLevelsUp.FullName;;

Upvotes: 2

Related Questions