Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with relative file paths in .Net

I have a C# project where I include some resources which I need to refer using the Uri-class. For this specific problem I have some shaders placed in a "Shaders" folder in the root of the project, but I've had this problem before with other files like images, etc. This far I've used the simple solution giving a fixed absolute path, and making sure the file is present at that location. Needless to say - this is not a good solution, and it won't work in the long run...

So, how can I use relative paths to refer my resources? I guess my question is twofold:

  • First; I don't want to refer the relative path from my Debug folder to the project folder. I want the file to be copied to the build folder. The shaders are included in the project, but obviously this isn't enough. How do I tell the project to copy the files when building? Or; what's the common way of solving this?

  • Second; when I have the "Shaders" folder copied to my build folder - what Uri syntax do I use to refer e.g. "myShader.ps" placed inside this folder? Can I simply say file:///Shaders/myShader.ps?

like image 366
stiank81 Avatar asked Nov 18 '09 21:11

stiank81


People also ask

How do you use relative paths?

Relative paths make use of two special symbols, a dot (.) and a double-dot (..), which translate into the current directory and the parent directory. Double dots are used for moving up in the hierarchy. A single dot represents the current directory itself.

How do I open a file with relative path?

A relative path contains the current directory and then the file name. The access mode specifies the operation you wanted to perform on the file, such as reading or writing. To open and read a file, use the r access mode. To open a file for writing, use the w mode.

Why is it better to use relative paths instead of absolute paths?

Relative links show the path to the file or refer to the file itself. A relative URL is useful within a site to transfer a user from point to point within the same domain. Absolute links are good when you want to send the user to a page that is outside of your server.


2 Answers

To get a Uri from your applications directory do:

Uri baseUri = new Uri(System.Reflection.Assembly.GetEntryAssembly().Location);
Uri shader = new Uri(baseUri, "shaders/test.ps");
like image 50
tyranid Avatar answered Sep 21 '22 02:09

tyranid


Answer to first:

How do I tell the project to copy the files when building?

Add the file to the project, right click, select Properties and change Copy to Output Directory to Always Copy.

like image 40
Mark Byers Avatar answered Sep 22 '22 02:09

Mark Byers