Mukesh Rawat
Mukesh Rawat

Reputation: 2097

Ways to get the relative path of a folder

I have one folder named "Images" in my project. I want to get the path of the Image folder so that I can browse that and get the files.

I'm using below piece of code for my above requirement and it is working fine.

string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(@"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
  foreach (string fileName in fileEntries)
         listBox.Items.Add(fileName);

Just want to know like is there any elegant way of doing this? What are the best ways of getting the folder path?

Upvotes: 0

Views: 1622

Answers (2)

Botz3000
Botz3000

Reputation: 39600

This is what i usually use:

string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Note that this returns the directory of the assembly that contains the currently executing code (i assume this is your main executable).

To get the parent directory of the resulting path, you can also use

Path.GetDirectoryName(appDirectory);

I would advice against depending on the Visual Studio project structure in your code, though. Consider adding the images folder as content to your application, so that it resides in a subdirectory in the same directory as your executable.

Upvotes: 4

Will Dean
Will Dean

Reputation: 39500

If you are just trying to reference a directory with a fixed relationship to another, then you can just use the same .. syntax you'd use at the command line?

You should also use the methods in the Path class (eg Path.Combine) rather than all that string manipulation.

Upvotes: 1

Related Questions