Working with relative file paths in .Net - c#

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?

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

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.

Related

How to access a subfolder within a asp.net (C#) Project, WebApi

I have a seemingly basic question, but I can't access a folder inside my project (actually, it is a project that is one of the references of the main project), which is a folder called "pdfs" that contains 1 PDF that I want to convert to base64.
I put the "pdfs" folder in the same level of the file from where I call it, as I thought it would be easier to access (actionDB.cs file, which is in services/actions/actionDB.cs). The "pdfs" folder is in services/actions/pdfs).
But there is no way to get the correct path of this folder.
On the contrary, if I put the folder in c: , getting path = "c:\\pdfs", and the pdf file there, I can easily find it and convert the pdf perfectly in the code.
Any idea how to access these folders that are inside the projects, as if they were assets? I already put 'copy always: to the destination' and 'type of compilation: content' in the pdf properties, but I still can't access it.
I have already tried the following options:
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"pdfs");
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"services\actions\pdfs");
string path = Path.Combine(Path.GetDirectoryName(Environment.CurrentDirectory), #"services\actions\pdfs");
The namespace of the actionsDB is ProjectName.Data.services.actions.
I got results such as IIS/.., or other paths inside VS installation…, Assembly and some weird hashes.
Nothing works...
Could you help me with this?
Thank you very much,
CBD
AppDomain.CurrentDomain.BaseDirectory is probably the most useful for accessing files whose location is relative to the application install directory.

C# get relative path of resources folder

I want to acess a .txt file, which I stored in the resources folder of my project, there where all the imported pictures are stored as well.
I want to use something like a relative path, since every user would have safed his programm somewehere else on his Pc, but there is always the resources folder at the same place, compared to the programm folder.
I tried to used this: displayText = System.IO.File.ReadAllText("Resources\\startmessages.txt"); but this isn't working.
I get this error message: System.IO.DirectoryNotFoundException:, it lists the unrelative path to the .txt there as well, so I don't get, why it cant read it.
Thanks for your Help.
What #ChetanRanpariya is trying to tell you is, that your programm is built in another folder than your folder Resources is sitting to. So you have explictly tell your file Resources\startmessages.txt to copy itself on build process, so it get copied to said another folder. Assuming that you are using Visual Studio, you have to right click on your file and set Copy To Output Directory to true. Its relative folder path (Resources\) will be taken over. You find your build folder somewhere in your bin folder depending on configuration and framework. :)
Current Path where your executable is
Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).FullName
Path to Solution
If you are using Visual Studio and need to access the folders in the solution directory, you can use .Parent method,
Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName
Use of Path.Combine
and once you have the location of your Resource folder, use Path.Combine to get the location to read files / content etc
Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Resources\\startMessages.txt")

System.IO.Path.Combine(Environment.CurrentDirectory,"") takes me to wrong path

I am loading this file which is located in a folder i created, the same folder is also rendered in the bin/debug folder, but i need to locate the file in the folder i created, the thing is the method which should find the path of the file by its name gives me the path of the debug folder instead of the on i created.
I have harcoded the path to show you the real location.
var path2 = System.IO.Path.Combine(Environment.CurrentDirectory, "xulrunner");
var hardcodedPath= "C:\\Users\\Alan\\Desktop\\TabControl\\TabControl\\TabControl\\TabControl\\xulrunner";
This is the result of path2 variable:
C:\\Users\\Alan\\Desktop\\TabControl\\TabControl\\TabControl\\TabControl\\bin\\Debug\\xulrunner"
As you can see its pointing to different folder as hardcoded path.
When running from Visual Studio, the working directory is different from your project location, usually it is two folders up (from bin\Debug\). In your distributed application, the working directory might be the same as that of other files you want to access since you copy some other files to the working directory.
I would recommend to keep your code the same, and copy the files you require from your project to the output directory. You can do that by simply setting the Copy to Output Directory setting to Copy always or Copy if newer.
Changing the path to go two folders up is a bad idea, since this won't be true in production scenarios, and will thus break your code.
To get exactly what you are looking for, you could do the following:
var path2 = System.IO.Path.GetFullPath(System.IO.Path.Combine(Environment.CurrentDirectory, "..\\..\\xulrunner"));
However, please be aware that Environment.CurrentDirectory can change as your program runs. I have found that using the %PROGRAMDATA% environment variable works well for creating a location where you save data. It allows for a more consistent solution for using paths.
Additionally, the code snippet provided will only really be useful when you are running through the IDE's debugger. When you deploy, it will likely not give you what you are expecting.
It would help to know what is the overall functional result you are hoping for.

Relative paths in C#

I need some help with paths please!
Basically I have a project with the following folder structure:
Project (root directory which contains the .sln file etc.)
Project/MyProj (contains the code)
Project/MyProjTest (the test folder)
Project/TestResults
Now with this Project I need to have a common folder where I can stick a bunch of files for use with the Application without having to copy the files to multiple locations etc. What is the best way to do this? Ideally I would like to have the folder as Project/ResourcesFolder, so that both the Code folder and Test folder can access it. Now if this is the case how do I call this folder from within C#? I've tried Application.StartupPath, Environment.GetCurrentDirectory but they both just return the CURRENT folder which is not what I want.
Thanks in advance.
You can add a solution folder to your solution and place common files in it.
You'll have to copy the files, you'll want your program to operate the same way after it is deployed. The simplest way to do so is by adding them to your project. In the Properties window, set Build Action = None, Copy to Output Directory = Copy if Newer. The latter setting ensures that you don't waste time copying the files over and over again.
This ensures that the files will be present in the same directory as your EXE. Both when you debug and after you deploy it. Simply use Application.StartupPath to locate them. Creating the Setup project for the app is now very simple as well.
Note that if the files are small you really want to embed them as resources.
.. goes one directory up. That is, from Project/MyProjTest you could access Project/MyProj via ../MyProj.
Use Server.MapPath("~") to get to the root folder of your application. From there you can get to wherever you need.

Loading Content images from Blend from separate project

I have a VS2010 solution with 5 projects. Two of these projects are called:
MyResources
Application
The Application project contains all of the views and viewmodels for the application to run, and the Resources project contains all the images, resource dictionaries, etc for theming and skinning.
The way I have images set up in Resources, I have their build action set to Content, and Copy set to Copy Always. In my Application project, I reference these files using a pack URI. Example:
"pack://siteoforigin:,,,/Themes/DefaultTheme/BackgroundImage.png"
This works fine for me. The themes folder and all its subfolders are properly copied to the proper folder since I'm using siteoforigin://.
However, this breaks Blendability. When I load the project in Blend 4, I get errors.
If I use siteoforigin, Blend tries to load the images from the executing folder of blend.exe (In this case, C:\Program Files\Microsoft Expression\Blend 4 Beta\Themes\Default_Theme\BackgroundImage.png")
If I change the pack URI to the following:
pack://application:,,,/IQ.IQKiosk.Resources;component/Themes/DefaultTheme/BackgroundImage.png
It tries to look for the image in "themes/default_theme/backgroundimage.png"
If I try:
/MyResources;component/Themes/DefaultTheme/BackgroundImage.png
It tries to look for the image in "C:\MyResources;component\Themes\DefaultTheme\BackgroundImage.png"
If I try:
/Themes/DefaultTheme/BackgroundImage.png
It tries to look for the image in "C:\Themes\DefaultTheme\BackgroundImage.png".
So now I'm stuck. I'm not sure how to reference my images without having to embed them into the resource project, and I can't hard code the directory because my other coworkers have the project in different folders as well.
I tried to think of a way to get the proper URI to the proper locations of the files (relative to the .sln file would be awesome) or have the files get copied over to where blend compiles and executes the project. Alas, I am unable to figure out how.
Does anyone know the proper way to get these images to load?
I figured it out. Instead of using a pack URI, I just used
new Uri(Environment.CurrentDirectory + "\\Themes\\DefaultTheme\\BackgroundImage.png")
and it found the proper folder, since Evironment.CurrentDirectory gave me the proper bin folder where my themes were copied to.
Huzzah!

Categories