Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get resources folder path c#

Tags:

c#

path

Some resources I have in my project are fine and working Ok using string paths but what if I move the project to another directory or to another computer, it will stop working.

Please I need to get the path of the resources folder of my project in a string variable,

Something like this

C:\Users\User1\Documents\<projects folder>\<project name>\Resources\

Thanks in advance.

like image 262
Isaac Tuncar Cedron Avatar asked Nov 28 '14 04:11

Isaac Tuncar Cedron


3 Answers

If you know the path relative to where the app is running, you can do something like this. First, get the app's running path:

string RunningPath = AppDomain.CurrentDomain.BaseDirectory;

Then, get navigate to the relative path using something like this:

string FileName = string.Format("{0}Resources\\file.txt", Path.GetFullPath(Path.Combine(RunningPath, @"..\..\")));

In this example I my "Resources" folder is located two directories up from my running one.

I should also mention, that if your resource is included in the project, you should be able to get it using:

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();

this will return an array of your resources.

like image 173
Jay M Avatar answered Nov 19 '22 07:11

Jay M


If the files are stored in your project folder, you can retrieve the files using System.AppDomain.CurrentDomain.BaseDirectory. This statement retrieves the path as to where your application is installed. Click Here to get a detailed explanation on this.

like image 12
Tejus Avatar answered Nov 19 '22 07:11

Tejus


This might not be the cleanest way, but it has been useful to me.

If you had a structure like:

C:\...\MyApp\app.exe
C:\...\MyApp\ConfigFiles\MyConfig.xml

The code will return a path relative to the running assembly.

GetPath("ConfigFiles/MyConfig.xml") // returns the full path to MyConfig.xml

private string GetPath(string relativePath)
{
    var appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    string pattern = @"^(.+\\)(.+exe)$";
    Regex regex = new Regex(pattern, RegexOptions.None);
    var match = regex.Match(appPath);
    return System.IO.Path.GetFullPath(match.Groups[1].Value + relativePath);
}
like image 3
NachoMK Avatar answered Nov 19 '22 09:11

NachoMK